Skip to content
Open
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
3 changes: 1 addition & 2 deletions front-end/src/renderer/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,7 @@ useWebsocketSubscription(TRANSACTION_ACTION, async (payload?: unknown) => {
if (isLoggedInOrganization(user.selectedOrganization)) {
const serverUrl = user.selectedOrganization.serverUrl;
for (const transactionId of parsed.transactionIds) {
// We clear cache with strict==false to keep young data
appCache.backendTransaction.forget(transactionId, serverUrl, false);
appCache.backendTransaction.forget(transactionId, serverUrl);
}
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ import { getTransactionById } from '@renderer/services/organization';
import type { ITransactionFull } from '@shared/interfaces';

export class BackendTransactionCache extends EntityCache<number | string, ITransactionFull> {
// Transactions are mutable and status-bearing: keep entries short-lived so that
// a missed websocket event can only leave stale data for a few seconds.
public static readonly TTL = 10_000; // ms

public constructor() {
super(BackendTransactionCache.TTL);
}

//
// Public
//
Expand Down
11 changes: 2 additions & 9 deletions front-end/src/renderer/caches/base/EntityCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,8 @@ export abstract class EntityCache<K extends string | number, E> {
return result;
}

public forget(key: K, mirrorNodeUrl: string, strict = true): void {
const recordKey = this.makeRecordKey(key, mirrorNodeUrl);
const currentRecord = this.records.get(recordKey);
if (currentRecord) {
// When strict is off, we forget only if data is 1s old (help for notification mgt)
if (strict || currentRecord.age() > 1000) {
this.records.delete(recordKey);
}
}
public forget(key: K, mirrorNodeUrl: string): void {
this.records.delete(this.makeRecordKey(key, mirrorNodeUrl));
Comment on lines +33 to +34
}

public clear(): void {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,8 +313,7 @@ async function fetchTransactionOnNotif(): Promise<void> {
// 1) Before calling fetchTransaction(), we clear transaction cache
const id = Number(formattedId.value);
if (isLoggedInOrganization(user.selectedOrganization) && !isNaN(id)) {
// We clear cache with strict==false to keep young data
appCache.backendTransaction.forget(id, user.selectedOrganization.serverUrl, false);
appCache.backendTransaction.forget(id, user.selectedOrganization.serverUrl);
}
// 2) Now fetch transaction
await fetchTransaction();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -462,8 +462,7 @@ async function fetchGroupOnNotif(groupId: string | number) {
if (isLoggedInOrganization(user.selectedOrganization) && group.value !== null) {
const serverUrl = user.selectedOrganization.serverUrl;
for (const item of group.value.groupItems) {
// We clear cache with strict==false to keep young data
appCache.backendTransaction.forget(item.transactionId, serverUrl, false);
appCache.backendTransaction.forget(item.transactionId, serverUrl);
}
}
// 2) Now fetch group
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -274,8 +274,7 @@ async function fetchTransactionsOnNotif(options?: { silent?: boolean }) {
if (isLoggedInOrganization(user.selectedOrganization)) {
const serverUrl = user.selectedOrganization.serverUrl;
for (const t of organizationTransactions.value) {
// We clear cache with strict==false to keep young data
transactionCache.forget(t.transactionRaw.transactionId, serverUrl, false);
transactionCache.forget(t.transactionRaw.transactionId, serverUrl);
}
}
// 2) Now fetch group
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -303,9 +303,8 @@ async function fetchNodesOnNotif(options?: { silent?: boolean }): Promise<void>
if (isLoggedInOrganization(user.selectedOrganization)) {
const serverUrl = user.selectedOrganization.serverUrl;
for (const node of nodes.value) {
// We clear cache with strict==false to keep young data
if (node.transactionId) {
transactionCache.forget(node.transactionId, serverUrl, false);
transactionCache.forget(node.transactionId, serverUrl);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { EntityCache } from '@renderer/caches/base/EntityCache';
import { BackendTransactionCache } from '@renderer/caches/backend/BackendTransactionCache';
import { getTransactionById } from '@renderer/services/organization';
import type { ITransactionFull } from '@shared/interfaces';

vi.mock('@renderer/services/organization', () => ({ getTransactionById: vi.fn() }));

const URL = 'https://org.example.com';
const SDK_ID = '0.0.2@1700000000.000000000';

const makeTx = (status: string): ITransactionFull =>
({ id: 7, transactionId: SDK_ID, status }) as unknown as ITransactionFull;

describe('BackendTransactionCache', () => {
const getMock = vi.mocked(getTransactionById);
let cache: BackendTransactionCache;

beforeEach(() => {
vi.useFakeTimers();
getMock.mockReset();
cache = new BackendTransactionCache();
});

afterEach(() => {
vi.useRealTimers();
});

// Note: this checks behaviour only. The original bug was in the call sites (forget(id, url, false)
// skipped entries younger than 1s), which this cache API no longer allows.
test('an event right after a fetch invalidates the entry (issue #3733)', async () => {
// Client fetches while the transaction is still waiting for execution...
getMock.mockResolvedValue(makeTx('WAITING_FOR_EXECUTION'));
await cache.lookup(7, URL);

// ...and the status-update event arrives well within a second of that fetch
vi.advanceTimersByTime(300);
cache.forget(7, URL);

getMock.mockResolvedValue(makeTx('EXECUTED'));
expect((await cache.lookup(7, URL)).status).toBe('EXECUTED');
});

test('concurrent lookups share a single fetch', async () => {
let resolve!: (tx: ITransactionFull) => void;
getMock.mockReturnValue(new Promise(r => (resolve = r)));

const first = cache.lookup(7, URL);
const second = cache.lookup(7, URL);
resolve(makeTx('WAITING_FOR_EXECUTION'));

expect(await first).toBe(await second);
expect(getMock).toHaveBeenCalledTimes(1);
});

test('an entry is served from cache until the TTL, then refetched', async () => {
getMock.mockResolvedValue(makeTx('WAITING_FOR_EXECUTION'));
await cache.lookup(7, URL);

vi.advanceTimersByTime(BackendTransactionCache.TTL - 1_000);
await cache.lookup(7, URL);
expect(getMock).toHaveBeenCalledTimes(1);

// An entry stays usable for TTL + FRESH_DURATION
vi.advanceTimersByTime(1_000 + EntityCache.FRESH_DURATION);
await cache.lookup(7, URL);
expect(getMock).toHaveBeenCalledTimes(2);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ import { flushPromises, mount } from '@vue/test-utils';
import { type ITransactionFull, TransactionStatus } from '@shared/interfaces';
import TransactionDetails from '@renderer/pages/TransactionDetails/TransactionDetails.vue';
import { ToastManager } from '@renderer/utils/ToastManager.ts';
import useWebsocketSubscription from '@renderer/composables/useWebsocketSubscription';

const toastManager = new ToastManager();

const { lookupMock, computeSignatureKeyMock } = vi.hoisted(() => ({
const { lookupMock, forgetMock, computeSignatureKeyMock } = vi.hoisted(() => ({
lookupMock: vi.fn(),
forgetMock: vi.fn(),
computeSignatureKeyMock: vi.fn().mockResolvedValue(null),
}));

Expand Down Expand Up @@ -98,7 +100,7 @@ vi.mock('@shared/constants', async importOriginal => {
vi.mock('@renderer/caches/AppCache.ts', () => ({
AppCache: {
inject: () => ({
backendTransaction: { lookup: lookupMock },
backendTransaction: { lookup: lookupMock, forget: forgetMock },
computeSignatureKey: computeSignatureKeyMock,
}),
},
Expand Down Expand Up @@ -197,11 +199,47 @@ const mountTransactionDetails = async (orgTransaction: ITransactionFull) => {
describe('TransactionDetails.vue review warnings', () => {
beforeEach(() => {
lookupMock.mockReset();
forgetMock.mockReset();
computeSignatureKeyMock.mockReset().mockResolvedValue(null);
toastManager.reset();
routerMock.previousTab = undefined;
});

test('a status-update event for this transaction drops the cached entry and refetches', async () => {
await mountTransactionDetails(
makeOrgTransaction({ status: TransactionStatus.WAITING_FOR_EXECUTION }),
);
expect(lookupMock).toHaveBeenCalledTimes(1);

lookupMock.mockResolvedValue(makeOrgTransaction({ status: TransactionStatus.EXECUTED }));
const onAction = vi.mocked(useWebsocketSubscription).mock.calls.at(-1)![1] as (
payload?: unknown,
) => Promise<void>;
await onAction([{ transactionIds: [101], groupIds: [], eventType: 'status_update' }]);
await flushPromises();

expect(forgetMock).toHaveBeenCalledWith(101, 'https://org.example.com');
expect(lookupMock).toHaveBeenCalledTimes(2);
expect(forgetMock.mock.invocationCallOrder[0]).toBeLessThan(
lookupMock.mock.invocationCallOrder[1],
);
});

test('an event for a different transaction does not touch the cache', async () => {
await mountTransactionDetails(
makeOrgTransaction({ status: TransactionStatus.WAITING_FOR_EXECUTION }),
);
const onAction = vi.mocked(useWebsocketSubscription).mock.calls.at(-1)![1] as (
payload?: unknown,
) => Promise<void>;

await onAction([{ transactionIds: [999], groupIds: [], eventType: 'status_update' }]);
await flushPromises();

expect(forgetMock).not.toHaveBeenCalled();
expect(lookupMock).toHaveBeenCalledTimes(1);
});

test('shows no banner when there is no rejection and the transaction is not pending review', async () => {
const wrapper = await mountTransactionDetails(
makeOrgTransaction({ status: TransactionStatus.WAITING_FOR_SIGNATURES, reviewerLists: [] }),
Expand Down
Loading