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
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import { PerpsMarketListPage } from '../pages/perps/perps-market-list-page';
* After a simulated position change in E2E, pushes a `userFills` snapshot via
* `pushUserFills`, then opens Perps Activity and asserts a trade row appears
* with the expected title fragment (same navigation pattern as other lifecycle tests).
* `pushUserFills` must also make the mocked `userFills` REST read return the fill:
* opening Activity force-refreshes history, so that read is what the page renders
* regardless of whether the live stream delivered the push.
*
* @param options
* @param options.driver
Expand Down Expand Up @@ -39,10 +42,6 @@ export async function assertPerpsActivityShowsCloseFill({
const perpsTab = new PerpsTab(driver);
await perpsTab.navigateToPerpsHome();
await perpsTab.waitForPerpsViewStable();
// Activity only shows a just-closed trade via the live fill (REST history is
// cached for 60s), and the wallet can drop a fill that arrives while leaving
// market detail. Push it again so the trade reliably reaches Activity.
pushUserFills();
await perpsTab.waitForRecentActivitySection();
await perpsTab.clickRecentActivitySeeAll();

Expand Down
50 changes: 46 additions & 4 deletions ui/hooks/perps/coalesceBackgroundRequest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,9 @@ describe('coalesceBackgroundRequest', () => {
});

it('invalidate() mid-flight preserves the in-flight promise so concurrent callers coalesce into one request', async () => {
// Rapid-navigation scenario: hook A fires a request, then hook B's
// forceFreshOnMount refetch invalidates the cache while A is still
// in flight. B must share A's request rather than fire a duplicate HL
// call — the in-flight snapshot is the freshest data available.
// Rapid navigation: hook A fires a request, then hook B invalidates the
// cache while A is still in flight. A caller that does not opt out shares
// A's request. A caller that cannot share it passes replaceInFlight.
let resolveFirst: ((v: string) => void) | undefined;
const firstPromise = new Promise<string>((resolve) => {
resolveFirst = resolve;
Expand Down Expand Up @@ -151,6 +150,49 @@ describe('coalesceBackgroundRequest', () => {
expect(fn).toHaveBeenCalledTimes(2);
});

it('replaceInFlight issues a new request and keeps that result in the cache', async () => {
let resolveFirst: ((value: string) => void) | undefined;
const firstPromise = new Promise<string>((resolve) => {
resolveFirst = resolve;
});
const fn = jest
.fn<Promise<string>, []>()
.mockReturnValueOnce(firstPromise)
.mockResolvedValueOnce('fresh');

const firstCall = coalesceBackgroundRequest('k', fn, 10_000);
await Promise.resolve();

const secondCall = coalesceBackgroundRequest('k', fn, 10_000, {
replaceInFlight: true,
});
resolveFirst?.('stale');

const [first, second] = await Promise.all([firstCall, secondCall]);
expect(first).toBe('stale');
expect(second).toBe('fresh');
expect(fn).toHaveBeenCalledTimes(2);

const cached = await coalesceBackgroundRequest('k', fn, 10_000);
expect(cached).toBe('fresh');
expect(fn).toHaveBeenCalledTimes(2);
});

it('replaceInFlight does not return a value cached inside the TTL', async () => {
const fn = jest
.fn<Promise<string>, []>()
.mockResolvedValueOnce('cached')
.mockResolvedValueOnce('fresh');

await coalesceBackgroundRequest('k', fn, 10_000);
const second = await coalesceBackgroundRequest('k', fn, 10_000, {
replaceInFlight: true,
});

expect(second).toBe('fresh');
expect(fn).toHaveBeenCalledTimes(2);
});

it('drops in-flight entry when fn throws synchronously so the next caller retries', async () => {
const fn = jest
.fn<Promise<string>, []>()
Expand Down
43 changes: 31 additions & 12 deletions ui/hooks/perps/coalesceBackgroundRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
* home; callers that need a tighter window pass their own TTL, as the Perps
* withdraw confirmation alert does at 5 s. Top-level consumers
* (`PerpsActivityPage`) pass `forceFreshOnMount` and bypass the cache
* entirely.
* entirely. A forced read also replaces an in-flight request for the same
* key: that request was started without `forceRefresh`, so joining it would
* return the controller's cached snapshot.
*
* Explicit refetch paths (pull-to-refresh) bypass the cache via invalidate().
* Scope-level teardown (account switch, testnet toggle, wallet lock,
Expand All @@ -28,6 +30,18 @@ const DEFAULT_TTL_MS = 10_000;

type CacheEntry<TValue> = { at: number; value: TValue };

/**
* Options for {@link coalesceBackgroundRequest}.
*/
export type CoalesceBackgroundRequestOptions = {
/**
* Issue `fn` even when this key has a cached or in-flight result, and take
* the in-flight slot. The replaced request still resolves for its own
* caller, but it no longer writes the cache.
*/
replaceInFlight?: boolean;
};

const cache = new Map<string, CacheEntry<unknown>>();
const inFlight = new Map<string, Promise<unknown>>();

Expand All @@ -37,23 +51,29 @@ const inFlight = new Map<string, Promise<unknown>>();
* value.
*
* @param key - Stable key derived from the request method and its params.
* @param fn - Thunk that issues the underlying request. Only called on miss.
* @param fn - Thunk that issues the underlying request. Only called on miss,
* or when `options.replaceInFlight` is set.
* @param ttlMs - Optional override for the short-cache TTL.
* @param options - Optional call modifiers.
* @param options.replaceInFlight - Issue a new request and take the in-flight
* slot instead of joining one that is already running.
* @returns Resolved value from the request (fresh or cached).
*/
export async function coalesceBackgroundRequest<TResult>(
key: string,
fn: () => Promise<TResult>,
ttlMs: number = DEFAULT_TTL_MS,
options?: CoalesceBackgroundRequestOptions,
): Promise<TResult> {
const replaceInFlight = options?.replaceInFlight === true;
const now = Date.now();
const cached = cache.get(key) as CacheEntry<TResult> | undefined;
if (cached && now - cached.at < ttlMs) {
if (!replaceInFlight && cached && now - cached.at < ttlMs) {
return cached.value;
}

const existing = inFlight.get(key) as Promise<TResult> | undefined;
if (existing !== undefined) {
if (!replaceInFlight && existing !== undefined) {
return existing;
}

Expand All @@ -67,8 +87,8 @@ export async function coalesceBackgroundRequest<TResult>(
const promise: Promise<TResult> = Promise.resolve().then(async () => {
try {
const value = await fn();
// Only persist if this promise still owns the slot; invalidate() may
// have evicted us mid-flight in favor of a newer request.
// Only persist if this promise still owns the slot. A newer request may
// have taken it via replaceInFlight.
if (inFlight.get(key) === promise) {
cache.set(key, { at: Date.now(), value });
}
Expand All @@ -89,12 +109,11 @@ export async function coalesceBackgroundRequest<TResult>(
* the next coalesceBackgroundRequest() to hit the backend instead of serving
* the previous cached value.
*
* Intentionally leaves any in-flight promise alone: an in-flight request is
* by definition the freshest server snapshot being computed right now, so
* concurrent callers (e.g. a `refetch()` racing with a sibling hook's mount
* fetch) should coalesce into the same request rather than fire a duplicate
* HL call. Dropping the in-flight entry here was the root cause of duplicate
* request bursts during rapid navigation.
* Intentionally leaves any in-flight promise alone. Callers that can share
* that request join it, which avoids the duplicate HyperLiquid calls that
* dropping the slot caused during rapid navigation. A caller that must not
* share it, because the in-flight request was sent with different controller
* options, passes `replaceInFlight` on its own call.
*
* @param key - Key previously used with coalesceBackgroundRequest.
*/
Expand Down
123 changes: 119 additions & 4 deletions ui/hooks/perps/usePerpsTransactionHistory.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { renderHook, act } from '@testing-library/react';
import { renderHook, act, waitFor } from '@testing-library/react';
import type { Order, OrderFill, Funding } from '@metamask/perps-controller';
import { usePerpsTransactionHistory } from './usePerpsTransactionHistory';
import { resetCoalesceCacheForTests } from './coalesceBackgroundRequest';
Expand Down Expand Up @@ -202,20 +202,135 @@ describe('usePerpsTransactionHistory', () => {

expect(mockSubmitRequestToBackground).toHaveBeenCalledWith(
'perpsGetOrderFills',
[{ accountId: 'eip155:1:0xabc', aggregateByTime: false }],
[
{ accountId: 'eip155:1:0xabc', aggregateByTime: false },
{ forceRefresh: true },
],
);

expect(mockSubmitRequestToBackground).toHaveBeenCalledWith(
'perpsGetOrders',
[{ accountId: 'eip155:1:0xabc' }],
[{ accountId: 'eip155:1:0xabc' }, { forceRefresh: true }],
);

expect(mockSubmitRequestToBackground).toHaveBeenCalledWith(
'perpsGetFunding',
[{ accountId: 'eip155:1:0xabc', startTime: 1000, endTime: 2000 }],
[
{ accountId: 'eip155:1:0xabc', startTime: 1000, endTime: 2000 },
{ forceRefresh: true },
],
);
});

it('asks the controller to bypass its REST cache when forceFreshOnMount is set', async () => {
renderHook(() => usePerpsTransactionHistory({ forceFreshOnMount: true }));

await waitFor(() => {
expect(mockSubmitRequestToBackground).toHaveBeenCalledWith(
'perpsGetOrderFills',
[
{ accountId: undefined, aggregateByTime: false },
{ forceRefresh: true },
],
);
expect(mockSubmitRequestToBackground).toHaveBeenCalledWith(
'perpsGetOrders',
[{ accountId: undefined }, { forceRefresh: true }],
);
expect(mockSubmitRequestToBackground).toHaveBeenCalledWith(
'perpsGetFunding',
[
{
accountId: undefined,
startTime: undefined,
endTime: undefined,
},
{ forceRefresh: true },
],
);
});
});

it('sends forceRefresh while a passive read for the same key is still in flight', async () => {
let releasePassive: (() => void) | undefined;
const passiveGate = new Promise<void>((resolve) => {
releasePassive = resolve;
});

mockSubmitRequestToBackground.mockImplementation(
(method: string, args: unknown[]) => {
const resultByMethod: Record<string, unknown> = {
perpsGetOrderFills: mockFills,
perpsGetOrders: mockOrders,
perpsGetFunding: mockFunding,
};
const result = resultByMethod[method] ?? [];
const forced = Array.isArray(args) && args.length > 1;
return forced
? Promise.resolve(result)
: passiveGate.then(() => result);
},
);

const passive = renderHook(() => usePerpsTransactionHistory());

await waitFor(() => {
expect(mockSubmitRequestToBackground).toHaveBeenCalledWith(
'perpsGetOrderFills',
[{ accountId: undefined, aggregateByTime: false }],
);
});

const forced = renderHook(() =>
usePerpsTransactionHistory({ forceFreshOnMount: true }),
);

await waitFor(() => {
expect(mockSubmitRequestToBackground).toHaveBeenCalledWith(
'perpsGetOrderFills',
[
{ accountId: undefined, aggregateByTime: false },
{ forceRefresh: true },
],
);
expect(mockSubmitRequestToBackground).toHaveBeenCalledWith(
'perpsGetOrders',
[{ accountId: undefined }, { forceRefresh: true }],
);
expect(mockSubmitRequestToBackground).toHaveBeenCalledWith(
'perpsGetFunding',
[
{
accountId: undefined,
startTime: undefined,
endTime: undefined,
},
{ forceRefresh: true },
],
);
});

await act(async () => {
releasePassive?.();
});

await waitFor(() => {
expect(passive.result.current.isLoading).toBe(false);
expect(forced.result.current.isLoading).toBe(false);
});
});

it('keeps the controller REST cache for passive fetches', async () => {
renderHook(() => usePerpsTransactionHistory());

await waitFor(() => {
expect(mockSubmitRequestToBackground).toHaveBeenCalledWith(
'perpsGetOrderFills',
[{ accountId: undefined, aggregateByTime: false }],
);
});
});

it('enriches fills with detailedOrderType from orders', async () => {
const fillWithOrderId: OrderFill[] = [
{
Expand Down
Loading
Loading