diff --git a/src/domain/api/eligibility-cache.test.ts b/src/domain/api/eligibility-cache.test.ts index c4da1b37..e165dfa3 100644 --- a/src/domain/api/eligibility-cache.test.ts +++ b/src/domain/api/eligibility-cache.test.ts @@ -1,11 +1,4 @@ -import { - clearCache, - createKey, - deleteCache, - getCache, - isMoreThanOneHourAgo, - setCache, -} from '@/domain/api/eligibility-cache' +import { createKey, readCache, setCache } from '@/domain/api/eligibility-cache' import type { EligibilityInput } from '@/domain/api/eligibility.types' import { mockButtonPlans } from '@/test/fixtures/plans' @@ -20,19 +13,9 @@ vi.mock('@/config/build-version.const', () => ({ }, })) +const HOUR = 3600000 const SANDBOX = 'https://api.sandbox.getalma.eu' -describe('isMoreThanOneHourAgo', () => { - it.each([ - { age: 3600001, expected: true }, - { age: 3600000, expected: true }, - { age: 3599999, expected: false }, - { age: 1000, expected: false }, - ])('should return $expected for a timestamp $age ms ago', ({ age, expected }) => { - expect(isMoreThanOneHourAgo(Date.now() - age)).toBe(expected) - }) -}) - describe('createKey', () => { const input = (overrides: Partial = {}): EligibilityInput => ({ domain: SANDBOX, @@ -66,11 +49,11 @@ describe('createKey', () => { }) buildVersion.current = '3.1.0' setCache(createKey(input()), mockButtonPlans) - expect(getCache(createKey(input()))).not.toBeNull() + expect(readCache(createKey(input()))).not.toBeNull() buildVersion.current = '3.1.1' - expect(getCache(createKey(input()))).toBeNull() + expect(readCache(createKey(input()))).toBeNull() }) it('keeps the key order of the plans as given', () => { @@ -82,60 +65,100 @@ describe('createKey', () => { }) }) -describe('the cache functions', () => { - it('should call the dedicated sessionStorage functions', () => { - expect(getCache('someKey')).toEqual(null) +describe('setCache', () => { + it('stores the value and the write time', () => { + setCache('key', []) + expect(sessionStorage.getItem('key')).toBe('{"value":[],"timestamp":1638350762000}') + }) + + it('reads back what it wrote, whatever the other keys', () => { setCache('someKey', mockButtonPlans) + setCache('otherKey', [mockButtonPlans[0]]) - // Date.now() is fixed by src/test/setup.ts. - expect(getCache('someKey')).toStrictEqual({ - value: mockButtonPlans, - timestamp: 1638350762000, + expect(readCache('someKey')).toEqual(mockButtonPlans) + expect(readCache('otherKey')).toEqual([mockButtonPlans[0]]) + }) + + it('lets a storage error through', () => { + const error = new DOMException('The quota has been exceeded.', 'QuotaExceededError') + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw error }) + expect(() => setCache('key', [])).toThrow(error) + }) +}) - setCache('otherKey', [mockButtonPlans[0]]) +describe('readCache', () => { + const seed = (entry: unknown) => sessionStorage.setItem('key', JSON.stringify(entry)) - deleteCache('someKey') - expect(getCache('someKey')).toEqual(null) - expect(getCache('otherKey')).toStrictEqual({ - value: [mockButtonPlans[0]], - timestamp: 1638350762000, - }) + it('returns the plans of a fresh entry', () => { + setCache('key', mockButtonPlans) + expect(readCache('key')).toEqual(mockButtonPlans) + }) - clearCache() - expect(getCache('otherKey')).toEqual(null) + it('returns null for a missing entry', () => { + expect(readCache('key')).toBeNull() }) - it('stores the value and the write time', () => { - setCache('key', []) - expect(sessionStorage.getItem('key')).toBe('{"value":[],"timestamp":1638350762000}') + it('keeps an entry without timestamp, which never expires', () => { + seed({ value: mockButtonPlans }) + expect(readCache('key')).toEqual(mockButtonPlans) + }) + + it.each([ + { age: HOUR + 1, expired: true }, + { age: HOUR, expired: true }, + { age: HOUR - 1, expired: false }, + ])('treats an entry written $age ms ago as expired: $expired', ({ age, expired }) => { + seed({ value: mockButtonPlans, timestamp: Date.now() - age }) + + expect(readCache('key')).toEqual(expired ? null : mockButtonPlans) + expect(sessionStorage.getItem('key') === null).toBe(expired) }) - it('clears the keys that the widget did not write', () => { + it('deletes only the expired entry', () => { sessionStorage.setItem('merchant-cart', 'keep me') - clearCache() - expect(sessionStorage.length).toBe(0) + seed({ value: mockButtonPlans, timestamp: Date.now() - HOUR }) + readCache('key') + expect(sessionStorage.getItem('merchant-cart')).toBe('keep me') }) - it('throws for an entry that is not JSON', () => { - sessionStorage.setItem('key', '{not json') - expect(() => getCache('key')).toThrow(SyntaxError) + it.each([ + ['an expired entry with no value', { timestamp: Date.now() - HOUR }], + ['an entry with an empty value', null], + ])('returns null for %s', (_, entry) => { + seed(entry) + expect(readCache('key')).toBeNull() }) - it('lets each sessionStorage error through', () => { + it.each([ + ['a value that is not an array', JSON.stringify({ value: { installments_count: 3 } })], + ['a value that is a string', JSON.stringify({ value: 'plans', timestamp: Date.now() })], + ['text that is not JSON', '{not json'], + ])('deletes a corrupt entry and returns null for %s', (_, raw) => { + sessionStorage.setItem('key', raw) + sessionStorage.setItem('merchant-cart', 'keep me') + + expect(readCache('key')).toBeNull() + expect(sessionStorage.getItem('key')).toBeNull() + expect(sessionStorage.getItem('merchant-cart')).toBe('keep me') + }) + + it('lets a storage error through when it reads', () => { const error = new DOMException('The operation is insecure.', 'SecurityError') - const fail = () => { + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw error - } - vi.spyOn(Storage.prototype, 'getItem').mockImplementation(fail) - vi.spyOn(Storage.prototype, 'setItem').mockImplementation(fail) - vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(fail) - vi.spyOn(Storage.prototype, 'clear').mockImplementation(fail) + }) + expect(() => readCache('key')).toThrow(error) + }) - expect(() => getCache('key')).toThrow(error) - expect(() => setCache('key', [])).toThrow(error) - expect(() => deleteCache('key')).toThrow(error) - expect(() => clearCache()).toThrow(error) + it('lets a storage error through when it deletes', () => { + const error = new DOMException('The operation is insecure.', 'SecurityError') + seed({ value: mockButtonPlans, timestamp: Date.now() - HOUR }) + vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => { + throw error + }) + expect(() => readCache('key')).toThrow(error) }) it('lets the error of a sessionStorage getter through', () => { @@ -147,7 +170,7 @@ describe('the cache functions', () => { }, }) try { - expect(() => getCache('key')).toThrow(DOMException) + expect(() => readCache('key')).toThrow(DOMException) } finally { Object.defineProperty(window, 'sessionStorage', descriptor as PropertyDescriptor) } diff --git a/src/domain/api/eligibility-cache.ts b/src/domain/api/eligibility-cache.ts index c310e367..5a836db3 100644 --- a/src/domain/api/eligibility-cache.ts +++ b/src/domain/api/eligibility-cache.ts @@ -4,7 +4,7 @@ import type { EligibilityInput } from '@/domain/api/eligibility.types' import type { EligibilityPlan } from '@/domain/plans.types' import { hashStringForStorage } from '@/lib/hash' -export const isMoreThanOneHourAgo = (date: number): boolean => Date.now() - date >= CACHE_TTL_MS +const isMoreThanOneHourAgo = (date: number): boolean => Date.now() - date >= CACHE_TTL_MS // A missing value prints as `undefined`, and the build version invalidates the entries of older // releases. Expects `purchaseAmount` to be set. @@ -24,23 +24,52 @@ export const createKey = ({ ) } -// These throw errors, and getEligibility() catches them. - // Any JSON value, unchecked, or null when there is no entry. -export const getCache = (key: string): unknown => { +const getCache = (key: string): unknown => { const stringData = sessionStorage.getItem(key) return stringData ? JSON.parse(stringData) : null } +const readEntryField = (entry: unknown, field: 'value' | 'timestamp'): unknown => + entry !== null && typeof entry === 'object' + ? (entry as Record)[field] + : undefined + export const setCache = (key: string, value: EligibilityPlan[]): void => { sessionStorage.setItem(key, JSON.stringify({ value, timestamp: Date.now() })) } -export const deleteCache = (key: string): void => { +const deleteCache = (key: string): void => { sessionStorage.removeItem(key) } -// Removes every key, the merchant's too. -export const clearCache = (): void => { - sessionStorage.clear() +// Deletes that entry only: the rest of sessionStorage is the merchant's. +const discardEntry = (key: string): null => { + deleteCache(key) + return null +} + +// The cached plans, or null when the request must go out. An expired or corrupt entry is deleted, +// so the request replaces it. Throws a storage error, which getEligibility() catches. +export const readCache = (key: string): EligibilityPlan[] | null => { + let entry: unknown + try { + entry = getCache(key) + } catch (error) { + // Only unparseable JSON is a corrupt entry. A storage error stays a failure. + if (error instanceof SyntaxError) { + return discardEntry(key) + } + throw error + } + const value = readEntryField(entry, 'value') + const timestamp = readEntryField(entry, 'timestamp') + // An entry without a timestamp never expires. + if (timestamp && isMoreThanOneHourAgo(timestamp as number)) { + return discardEntry(key) + } + if (!value) { + return null + } + return Array.isArray(value) ? value : discardEntry(key) } diff --git a/src/domain/api/get-eligibility.test.ts b/src/domain/api/get-eligibility.test.ts index 0e07f39d..38d7a256 100644 --- a/src/domain/api/get-eligibility.test.ts +++ b/src/domain/api/get-eligibility.test.ts @@ -64,34 +64,28 @@ describe('getEligibility', () => { }) describe('cache age', () => { - it('uses an entry without timestamp, which never expires', async () => { - seed({ value: mockPlansAllEligible }) - - expect((await getEligibility(input())).status).toBe(StatusResponse.SUCCESS) - expect(fetchFromApi).not.toHaveBeenCalled() - }) - - it('sends no request and stays pending for an expired entry', async () => { - seed({ value: mockPlansAllEligible, timestamp: Date.now() - HOUR }) - - expect(await getEligibility(input())).toEqual({ status: StatusResponse.PENDING, plans: [] }) - expect(fetchFromApi).not.toHaveBeenCalled() - }) - - it('sends the request when the expired entry has no value', async () => { - seed({ timestamp: Date.now() - HOUR }) + it('sends one request and rewrites the entry when it expired', async () => { + seed({ value: [mockPlansAllEligible[0]], timestamp: Date.now() - HOUR }) vi.mocked(fetchFromApi).mockResolvedValue(mockPlansAllEligible) - expect((await getEligibility(input())).status).toBe(StatusResponse.SUCCESS) + expect(await getEligibility(input())).toEqual({ + status: StatusResponse.SUCCESS, + plans: mockPlansAllEligible, + }) expect(fetchFromApi).toHaveBeenCalledTimes(1) + expect(JSON.parse(sessionStorage.getItem(createKey(input()))!)).toEqual({ + value: mockPlansAllEligible, + timestamp: Date.now(), + }) }) - it('sends the request for an entry with an empty value', async () => { - seed(null) - vi.mocked(fetchFromApi).mockResolvedValue([]) + it('sends one request for a corrupt entry', async () => { + sessionStorage.setItem(createKey(input()), '{not json') + vi.mocked(fetchFromApi).mockResolvedValue(mockPlansAllEligible) - expect(await getEligibility(input())).toEqual({ status: StatusResponse.SUCCESS, plans: [] }) + expect((await getEligibility(input())).status).toBe(StatusResponse.SUCCESS) expect(fetchFromApi).toHaveBeenCalledTimes(1) + expect(warn).not.toHaveBeenCalled() }) }) @@ -165,17 +159,9 @@ describe('getEligibility', () => { expect(warn).toHaveBeenCalledTimes(1) }) - it('fails with one warning when the clear of an expired entry throws', async () => { + it('fails with one warning when the delete of an expired entry throws', async () => { seed({ value: mockPlansAllEligible, timestamp: Date.now() - HOUR }) - vi.spyOn(Storage.prototype, 'clear').mockImplementation(throwing) - - expect(await getEligibility(input())).toEqual(FAILED) - expect(fetchFromApi).not.toHaveBeenCalled() - expect(warn).toHaveBeenCalledTimes(1) - }) - - it('fails with one warning and sends no request for a value that is not an array', async () => { - seed({ value: { installments_count: 3 }, timestamp: Date.now() }) + vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(throwing) expect(await getEligibility(input())).toEqual(FAILED) expect(fetchFromApi).not.toHaveBeenCalled() diff --git a/src/domain/api/get-eligibility.ts b/src/domain/api/get-eligibility.ts index d40c4063..e03a9b2d 100644 --- a/src/domain/api/get-eligibility.ts +++ b/src/domain/api/get-eligibility.ts @@ -1,29 +1,18 @@ -import { - clearCache, - createKey, - getCache, - isMoreThanOneHourAgo, - setCache, -} from '@/domain/api/eligibility-cache' +import { createKey, readCache, setCache } from '@/domain/api/eligibility-cache' import { buildEligibilityRequest } from '@/domain/api/eligibility-request-builder' import { StatusResponse } from '@/domain/api/eligibility.const' import type { EligibilityInput, EligibilityResult } from '@/domain/api/eligibility.types' +import type { EligibilityPlan } from '@/domain/plans.types' import { warnOnce } from '@/lib/errors' import { fetchFromApi } from '@/lib/http' const FAILED: EligibilityResult = { status: StatusResponse.FAILED, plans: [] } -const PENDING: EligibilityResult = { status: StatusResponse.PENDING, plans: [] } const fail = (message: string, error?: unknown): EligibilityResult => { warnOnce(message, error) return FAILED } -const readEntryField = (entry: unknown, field: 'value' | 'timestamp'): unknown => - entry !== null && typeof entry === 'object' - ? (entry as Record)[field] - : undefined - const requestEligibility = async (input: EligibilityInput): Promise => { let request try { @@ -53,40 +42,6 @@ const requestEligibility = async (input: EligibilityInput): Promise { - let cachedEntry: unknown - try { - cachedEntry = getCache(key) - } catch (error) { - return fail('The eligibility cache could not be read.', error) - } - const cached = readEntryField(cachedEntry, 'value') - const timestamp = readEntryField(cachedEntry, 'timestamp') - // An entry without a timestamp never expires. - const expired = Boolean(timestamp) && isMoreThanOneHourAgo(timestamp as number) - - if (expired) { - try { - clearCache() - } catch (error) { - return fail('The eligibility cache could not be cleared.', error) - } - // Sends no request and keeps loading until the next widget. - if (cached) { - return PENDING - } - } else if (cached) { - if (!Array.isArray(cached)) { - return fail('The eligibility cache entry is malformed.') - } - return { status: StatusResponse.SUCCESS, plans: cached } - } - - return null -} - // Cache first. Never rejects. A sent request always finishes and writes the cache. export const getEligibility = async (input: EligibilityInput): Promise => { const { purchaseAmount, configPlans } = input @@ -105,9 +60,14 @@ export const getEligibility = async (input: EligibilityInput): Promise