Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
139 changes: 81 additions & 58 deletions src/domain/api/eligibility-cache.test.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand All @@ -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> = {}): EligibilityInput => ({
domain: SANDBOX,
Expand Down Expand Up @@ -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', () => {
Expand All @@ -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', () => {
Expand All @@ -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)
}
Expand Down
45 changes: 37 additions & 8 deletions src/domain/api/eligibility-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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<string, unknown>)[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)
}
48 changes: 17 additions & 31 deletions src/domain/api/get-eligibility.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
})

Expand Down Expand Up @@ -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()
Expand Down
Loading