Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

12.4 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { AsyncCache } from '../src/asset/AsyncCache';

describe('AsyncCache', () => {
    let cache: AsyncCache<string>;

    beforeEach(() => {
        cache = new AsyncCache<string>();
    });

    it('clears its deadline when a loader rejects before timeout', async () => {
        vi.useFakeTimers();
        try {
            const error = new Error('load failed');
            await expect(cache.getOrLoad('deadline', async () => { throw error; }, 10000)).rejects.toBe(error);
            expect(vi.getTimerCount()).toBe(0);
        } finally { vi.useRealTimers(); }
    });

    describe('basic caching', () => {
        it('should cache successful results', async () => {
            const loader = vi.fn().mockResolvedValue('value');

            const result1 = await cache.getOrLoad('key', loader);
            const result2 = await cache.getOrLoad('key', loader);

            expect(result1).toBe('value');
            expect(result2).toBe('value');
            expect(loader).toHaveBeenCalledTimes(1);
        });

        it('should return cached value immediately', async () => {
            await cache.getOrLoad('key', async () => 'value');

            const loader = vi.fn();
            const result = await cache.getOrLoad('key', loader);

            expect(result).toBe('value');
            expect(loader).not.toHaveBeenCalled();
        });

        it('should cache multiple different keys', async () => {
            await cache.getOrLoad('key1', async () => 'value1');
            await cache.getOrLoad('key2', async () => 'value2');

            expect(await cache.getOrLoad('key1', async () => 'wrong')).toBe('value1');
            expect(await cache.getOrLoad('key2', async () => 'wrong')).toBe('value2');
        });
    });

    describe('pending promise deduplication', () => {
        it('should deduplicate concurrent requests', async () => {
            const loader = vi.fn().mockImplementation(async () => {
                await new Promise(resolve => setTimeout(resolve, 10));
                return 'value';
            });

            const [result1, result2, result3] = await Promise.all([
                cache.getOrLoad('key', loader),
                cache.getOrLoad('key', loader),
                cache.getOrLoad('key', loader),
            ]);

            expect(result1).toBe('value');
            expect(result2).toBe('value');
            expect(result3).toBe('value');
            expect(loader).toHaveBeenCalledTimes(1);
        });

        it('should handle concurrent requests for different keys', async () => {
            const loader1 = vi.fn().mockResolvedValue('value1');
            const loader2 = vi.fn().mockResolvedValue('value2');

            const [result1, result2] = await Promise.all([
                cache.getOrLoad('key1', loader1),
                cache.getOrLoad('key2', loader2),
            ]);

            expect(result1).toBe('value1');
            expect(result2).toBe('value2');
            expect(loader1).toHaveBeenCalledTimes(1);
            expect(loader2).toHaveBeenCalledTimes(1);
        });
    });

    describe('error handling', () => {
        it('should propagate errors from loader', async () => {
            const error = new Error('load failed');
            const loader = vi.fn().mockRejectedValue(error);

            await expect(cache.getOrLoad('key', loader)).rejects.toThrow('load failed');
        });

        it('should NOT cache failed promises', async () => {
            const loader = vi.fn()
                .mockRejectedValueOnce(new Error('first failure'))
                .mockResolvedValueOnce('success');

            await expect(cache.getOrLoad('key', loader)).rejects.toThrow('first failure');

            // Within cooldown, returns the cached error without calling loader
            await expect(cache.getOrLoad('key', loader)).rejects.toThrow('first failure');
            expect(loader).toHaveBeenCalledTimes(1);

            // After cooldown expires, retries with the loader
            vi.useFakeTimers();
            vi.advanceTimersByTime(6000);
            const result = await cache.getOrLoad('key', loader);
            vi.useRealTimers();

            expect(result).toBe('success');
            expect(loader).toHaveBeenCalledTimes(2);
        });

        it('should remove from pending on failure', async () => {
            const loader = vi.fn().mockRejectedValue(new Error('failed'));

            await expect(cache.getOrLoad('key', loader)).rejects.toThrow('failed');

            // After cooldown, allows retry with a new loader
            vi.useFakeTimers();
            vi.advanceTimersByTime(6000);
            const newLoader = vi.fn().mockResolvedValue('success');
            await cache.getOrLoad('key', newLoader);
            vi.useRealTimers();

            expect(newLoader).toHaveBeenCalled();
        });

        it('should handle concurrent failures correctly', async () => {
            const error = new Error('concurrent failure');
            const loader = vi.fn().mockRejectedValue(error);

            const promises = [
                cache.getOrLoad('key', loader),
                cache.getOrLoad('key', loader),
                cache.getOrLoad('key', loader),
            ];

            for (const promise of promises) {
                await expect(promise).rejects.toThrow('concurrent failure');
            }

            expect(loader).toHaveBeenCalledTimes(1);
        });

        it('should handle timeout', async () => {
            const loader = vi.fn().mockImplementation(async () => {
                await new Promise(resolve => setTimeout(resolve, 100));
                return 'value';
            });

            await expect(cache.getOrLoad('key', loader, 10)).rejects.toThrow('AsyncCache timeout');
        });
    });

    describe('has', () => {
        it('should return false for uncached keys', () => {
            expect(cache.has('key')).toBe(false);
        });

        it('should return true for cached keys', async () => {
            await cache.getOrLoad('key', async () => 'value');
            expect(cache.has('key')).toBe(true);
        });

        it('should return false for pending keys', () => {
            cache.getOrLoad('key', async () => {
                await new Promise(resolve => setTimeout(resolve, 100));
                return 'value';
            });

            expect(cache.has('key')).toBe(false);
        });

        it('should return false for failed keys', async () => {
            await expect(
                cache.getOrLoad('key', async () => { throw new Error('fail'); })
            ).rejects.toThrow();

            expect(cache.has('key')).toBe(false);
        });
    });

    describe('get', () => {
        it('should return undefined for uncached keys', () => {
            expect(cache.get('key')).toBeUndefined();
        });

        it('should return cached value', async () => {
            await cache.getOrLoad('key', async () => 'value');
            expect(cache.get('key')).toBe('value');
        });
    });

    describe('delete', () => {
        it('should remove cached entries', async () => {
            await cache.getOrLoad('key', async () => 'value');
            cache.delete('key');

            const loader = vi.fn().mockResolvedValue('new value');
            await cache.getOrLoad('key', loader);

            expect(loader).toHaveBeenCalled();
        });

        it('should handle deleting non-existent keys', () => {
            expect(cache.delete('nonexistent')).toBe(false);
        });

        it('should not affect pending promises', async () => {
            const loader = vi.fn().mockImplementation(async () => {
                await new Promise(resolve => setTimeout(resolve, 10));
                return 'value';
            });

            const promise = cache.getOrLoad('key', loader);
            cache.delete('key');

            const result = await promise;
            expect(result).toBe('value');
        });
    });

    describe('clear', () => {
        it('should remove all cached entries', async () => {
            await cache.getOrLoad('key1', async () => 'value1');
            await cache.getOrLoad('key2', async () => 'value2');

            cache.clear();

            expect(cache.has('key1')).toBe(false);
            expect(cache.has('key2')).toBe(false);
        });

        it('should not affect pending promises', async () => {
            const loader = vi.fn().mockImplementation(async () => {
                await new Promise(resolve => setTimeout(resolve, 10));
                return 'value';
            });

            const promise = cache.getOrLoad('key', loader);
            cache.clear();

            const result = await promise;
            expect(result).toBe('value');
        });
    });

    describe('clearAll', () => {
        it('should abort pending promises', async () => {
            const loader = vi.fn().mockImplementation(async () => {
                await new Promise(resolve => setTimeout(resolve, 100));
                return 'value';
            });

            const promise = cache.getOrLoad('key', loader);
            cache.clearAll();

            await expect(promise).resolves.toBe('value');
            expect(cache.has('key')).toBe(false);
        });
    });

    describe('complex scenarios', () => {
        it('should handle mixed success and failure', async () => {
            await cache.getOrLoad('success', async () => 'ok');
            await expect(
                cache.getOrLoad('failure', async () => { throw new Error('bad'); })
            ).rejects.toThrow();

            expect(cache.has('success')).toBe(true);
            expect(cache.has('failure')).toBe(false);
        });

        it('should handle retry after failure', async () => {
            const loader = vi.fn()
                .mockRejectedValueOnce(new Error('temp failure'))
                .mockResolvedValueOnce('success');

            await expect(cache.getOrLoad('key', loader)).rejects.toThrow('temp failure');

            // After cooldown, retries and succeeds
            vi.useFakeTimers();
            vi.advanceTimersByTime(6000);
            const result = await cache.getOrLoad('key', loader);
            vi.useRealTimers();

            expect(result).toBe('success');
            expect(cache.has('key')).toBe(true);
        });
    });

    describe('invalidate', () => {
        it('drops the cached value so next load fetches fresh', async () => {
            const loader = vi.fn()
                .mockResolvedValueOnce('v1')
                .mockResolvedValueOnce('v2');

            expect(await cache.getOrLoad('k', loader)).toBe('v1');
            expect(cache.invalidate('k')).toBe(true);
            expect(await cache.getOrLoad('k', loader)).toBe('v2');
            expect(loader).toHaveBeenCalledTimes(2);
        });

        it('returns false for a key that was never cached', () => {
            expect(cache.invalidate('missing')).toBe(false);
        });

        it('also clears the failure cooldown', async () => {
            const loader = vi.fn()
                .mockRejectedValueOnce(new Error('fail'))
                .mockResolvedValueOnce('ok');

            await expect(cache.getOrLoad('k', loader)).rejects.toThrow('fail');
            // Without invalidate, the cooldown would throw again.
            expect(cache.invalidate('k')).toBe(true);
            expect(await cache.getOrLoad('k', loader)).toBe('ok');
        });

        it('aborts an in-flight loader so the next getOrLoad starts a new one', async () => {
            let resolveFirst: (v: string) => void = () => {};
            const first = new Promise<string>(r => { resolveFirst = r; });
            const loader = vi.fn()
                .mockImplementationOnce(() => first)
                .mockResolvedValueOnce('v2');

            const p1 = cache.getOrLoad('k', loader);
            expect(cache.invalidate('k')).toBe(true);

            // Second call must not dedupe against the aborted first loader.
            const p2 = cache.getOrLoad('k', loader);
            resolveFirst('v1');

            // The aborted first loader still resolves but must not land in
            // the cache; the fresh load wins.
            await p1;
            expect(await p2).toBe('v2');
            expect(cache.get('k')).toBe('v2');
            expect(loader).toHaveBeenCalledTimes(2);
        });
    });
});