Skip to content

Commit

Permalink
feat(store): add debounce/throttle option
Browse files Browse the repository at this point in the history
allow to use debounce/throttle when updating stores

if there are 15 events in a row to update a store,
it can be updated only once after all events completed in like 1.5s

related to podman-desktop#3376
Signed-off-by: Florent Benoit <[email protected]>
  • Loading branch information
benoitf committed Aug 14, 2023
1 parent e17c7c3 commit 76948ac
Show file tree
Hide file tree
Showing 6 changed files with 235 additions and 26 deletions.
2 changes: 1 addition & 1 deletion packages/renderer/src/stores/containers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const containersEventStore = new EventStore<ContainerInfo[]>(
listContainers,
ContainerIcon,
);
containersEventStore.setup();
containersEventStore.setupWithDebounce();

export const searchPattern = writable('');

Expand Down
117 changes: 117 additions & 0 deletions packages/renderer/src/stores/event-store.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,120 @@ test('should call fetch method using listener event', async () => {
expect(eventStoreInfo.bufferEvents[0]).toHaveProperty('args', undefined);
expect(eventStoreInfo.bufferEvents[0]).toHaveProperty('length', 1);
});

test('Check debounce', async () => {
const myStoreInfo: Writable<MyCustomTypeInfo[]> = writable([]);
const checkForUpdateMock = vi.fn();

const windowEventName = 'my-custom-event';
const updater = vi.fn();

// return true to trigger the update
checkForUpdateMock.mockResolvedValue(true);

const eventStore = new EventStore('my-test', myStoreInfo, checkForUpdateMock, [windowEventName], [], updater);

// callbacks are empty
expect(callbacks.size).toBe(0);

// now call the setup with a debounce value of 200ms and no throttle
const eventStoreInfo = eventStore.setupWithDebounce(200, 0);

// check we have callbacks
expect(callbacks.size).toBe(1);

// now we call the listener
const callback = callbacks.get(windowEventName);
expect(callback).toBeDefined();

const myCustomTypeInfo: MyCustomTypeInfo = {
name: 'my-custom-type',
};
updater.mockResolvedValue([myCustomTypeInfo]);

// now, perform 20 calls every 50ms
for (let i = 0; i < 20; i++) {
await callback();
await new Promise(resolve => setTimeout(resolve, 50));
}

// wait debounce being called for 2 seconds
await new Promise(resolve => setTimeout(resolve, 2000));

// We did a lot of calls but with debounce, it should only be called once
expect(updater).toHaveBeenCalledOnce();

// check the store is updated
expect(get(myStoreInfo)).toStrictEqual([myCustomTypeInfo]);

// check the store is updated
expect(get(myStoreInfo)).toStrictEqual([myCustomTypeInfo]);

// check buffer events
expect(eventStoreInfo.bufferEvents.length).toBe(1);
expect(eventStoreInfo.bufferEvents[0]).toHaveProperty('name', windowEventName);
expect(eventStoreInfo.bufferEvents[0]).toHaveProperty('skipped', false);
expect(eventStoreInfo.bufferEvents[0]).toHaveProperty('args', undefined);
expect(eventStoreInfo.bufferEvents[0]).toHaveProperty('length', 1);
});

// check that we're still calling the update method
// every throttle even if we have lot of calls and are postponing with debounce
test('Check debounce+delay', async () => {
const myStoreInfo: Writable<MyCustomTypeInfo[]> = writable([]);
const checkForUpdateMock = vi.fn();

const windowEventName = 'my-custom-event';
const updater = vi.fn();

// return true to trigger the update
checkForUpdateMock.mockResolvedValue(true);

const eventStore = new EventStore('my-test', myStoreInfo, checkForUpdateMock, [windowEventName], [], updater);

// callbacks are empty
expect(callbacks.size).toBe(0);

// now call the setup with a debounce value of 200ms and a throttle of 1s
const eventStoreInfo = eventStore.setupWithDebounce(200, 1000);

// check we have callbacks
expect(callbacks.size).toBe(1);

// now we call the listener
const callback = callbacks.get(windowEventName);
expect(callback).toBeDefined();

const myCustomTypeInfo: MyCustomTypeInfo = {
name: 'my-custom-type',
};
updater.mockResolvedValue([myCustomTypeInfo]);

// now, perform 40 calls every 50ms
for (let i = 0; i < 20; i++) {
await callback();
await new Promise(resolve => setTimeout(resolve, 50));
}

// wait debounce being called for 3 seconds
await new Promise(resolve => setTimeout(resolve, 3000));

// We did a lot of calls but with debounce and throttle it should be only like 2 calls
// get number of calls
const calls = updater.mock.calls.length;
expect(calls).toBeGreaterThan(1);
expect(calls).toBeLessThanOrEqual(4);

// check the store is updated
expect(get(myStoreInfo)).toStrictEqual([myCustomTypeInfo]);

// check the store is updated
expect(get(myStoreInfo)).toStrictEqual([myCustomTypeInfo]);

// check buffer events
expect(eventStoreInfo.bufferEvents.length).toBeGreaterThan(1);
expect(eventStoreInfo.bufferEvents[0]).toHaveProperty('name', windowEventName);
expect(eventStoreInfo.bufferEvents[0]).toHaveProperty('skipped', false);
expect(eventStoreInfo.bufferEvents[0]).toHaveProperty('args', undefined);
expect(eventStoreInfo.bufferEvents[0]).toHaveProperty('length', 1);
});
136 changes: 114 additions & 22 deletions packages/renderer/src/stores/event-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,26 +25,33 @@ import { addStore, updateStore } from './event-store-manager';
import humanizeDuration from 'humanize-duration';
import DesktopIcon from '../lib/images/DesktopIcon.svelte';

export interface EventStoreInfo {
// 1.5 SECOND for DEBOUNCE and 5s for THROTTLE
const SECOND = 1000;
const DEFAULT_DEBOUNCE_TIMEOUT = 1.5 * SECOND;
const DEFAULT_THROTTLE_TIMEOUT = 5 * SECOND;

interface EventStoreInfoEvent {
name: string;

iconComponent?: ComponentType;
// args of the event
args: unknown[];

// list last 100 events
bufferEvents: {
name: string;
date: number;
// if the event was skipped
skipped: boolean;
length?: number;

// args of the event
args: unknown[];
// update time in ms
humanDuration?: number;
}

date: number;
// if the event was skipped
skipped: boolean;
length?: number;
export interface EventStoreInfo {
name: string;

// update time in ms
humanDuration?: number;
}[];
iconComponent?: ComponentType;

// list last 100 events
bufferEvents: EventStoreInfoEvent[];

// number of elements in the store
size: number;
Expand All @@ -59,6 +66,14 @@ export interface EventStoreInfo {
// Helper to manage store updated from events

export class EventStore<T> {
// debounce delay in ms. If set to > 0 , timeout before updating store value
// if there are always new requests, it will never update the store
// as we postpone the update until there is no new request
private debounceTimeoutDelay = 0;

// debounce always delay in ms. If set to > 0 , update after this delay even if some requests are pending.
private debounceThrottleTimeoutDelay = 0;

constructor(
private name: string,
private store: Writable<T>,
Expand All @@ -73,6 +88,15 @@ export class EventStore<T> {
}
}

protected updateEvent(eventStoreInfo: EventStoreInfo, event: EventStoreInfoEvent) {
// update the info object
eventStoreInfo.bufferEvents.push(event);
if (eventStoreInfo.bufferEvents.length > 100) {
eventStoreInfo.bufferEvents.shift();
}
updateStore(eventStoreInfo);
}

protected async performUpdate(
needUpdate: boolean,
eventStoreInfo: EventStoreInfo,
Expand Down Expand Up @@ -100,22 +124,26 @@ export class EventStore<T> {
this.store.set(result);
}
} finally {
// update the info object
eventStoreInfo.bufferEvents.push({
this.updateEvent(eventStoreInfo, {
name: eventName,
args: args,
date: Date.now(),
skipped: !needUpdate,
length: numberOfResults,
humanDuration: updateDuration,
});
if (eventStoreInfo.bufferEvents.length > 100) {
eventStoreInfo.bufferEvents.shift();
}
updateStore(eventStoreInfo);
}
}

setupWithDebounce(
debounceTimeoutDelay = DEFAULT_DEBOUNCE_TIMEOUT,
debounceThrottleTimeoutDelay = DEFAULT_THROTTLE_TIMEOUT,
): EventStoreInfo {
this.debounceTimeoutDelay = debounceTimeoutDelay;
this.debounceThrottleTimeoutDelay = debounceThrottleTimeoutDelay;
return this.setup();
}

setup(): EventStoreInfo {
const bufferEvents = [];

Expand All @@ -136,10 +164,74 @@ export class EventStore<T> {
};
addStore(eventStoreInfo);

// for debounce
let timeout: NodeJS.Timeout | undefined;
let timeoutEventName: string | undefined;

// for throttling every 5s if not already done
let timeoutThrottle: NodeJS.Timeout | undefined;

const update = async (eventName: string, args?: unknown[]) => {
const needUpdate = await this.checkForUpdate(eventName, args);
await this.performUpdate(needUpdate, eventStoreInfo, eventName, args);
// method that do the update
const doUpdate = async () => {
const needUpdate = await this.checkForUpdate(eventName, args);
await this.performUpdate(needUpdate, eventStoreInfo, eventName, args);
};

// no debounce, just do it
if (this.debounceTimeoutDelay <= 0) {
await doUpdate();
return;
}

// debounce timeout. If there is a pending action, cancel it and wait longer
if (timeout) {
clearTimeout(timeout);

this.updateEvent(eventStoreInfo, {
name: `debounce-${timeoutEventName}`,
args: args,
date: Date.now(),
skipped: true,
length: 0,
humanDuration: 0,
});

timeout = undefined;
timeoutEventName = eventName;
}
timeout = setTimeout(() => {
// cancel the throttleTimeout if any
if (timeoutThrottle) {
clearTimeout(timeoutThrottle);
timeoutThrottle = undefined;
}

doUpdate()
.catch((error: unknown) => {
console.error(`Failed to update ${this.name}`, error);
})
.finally(() => {
timeout = undefined;
});
}, this.debounceTimeoutDelay);

// throttle timeout, ask after 5s to update anyway to have at least UI being refreshed every 5s if there is a lot of events
// because debounce will defer all the events until the end so it's not so nice from UI side.
if (!timeoutThrottle && this.debounceThrottleTimeoutDelay > 0) {
timeoutThrottle = setTimeout(() => {
doUpdate()
.catch((error: unknown) => {
console.error(`Failed to update ${this.name}`, error);
})
.finally(() => {
clearTimeout(timeoutThrottle);
timeoutThrottle = undefined;
});
}, this.debounceThrottleTimeoutDelay);
}
};

this.windowEvents.forEach(eventName => {
window.events?.receive(eventName, async (args?: unknown[]) => {
await update(eventName, args);
Expand Down
2 changes: 1 addition & 1 deletion packages/renderer/src/stores/images.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ const imagesEventStore = new EventStore<ImageInfo[]>(
listImages,
ImageIcon,
);
imagesEventStore.setup();
imagesEventStore.setupWithDebounce();

export const searchPattern = writable('');

Expand Down
2 changes: 1 addition & 1 deletion packages/renderer/src/stores/pods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ const eventStore = new EventStore<PodInfo[]>(
grabAllPods,
PodIcon,
);
eventStore.setup();
eventStore.setupWithDebounce();

export async function grabAllPods(): Promise<PodInfo[]> {
let result = await window.listPods();
Expand Down
2 changes: 1 addition & 1 deletion packages/renderer/src/stores/volumes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const volumesEventStore = new EventStore<VolumeListInfo[]>(
listVolumes,
VolumeIcon,
);
const volumesEventStoreInfo = volumesEventStore.setup();
const volumesEventStoreInfo = volumesEventStore.setupWithDebounce();

export const searchPattern = writable('');

Expand Down

0 comments on commit 76948ac

Please sign in to comment.