Open-source Xbox-inspired desktop launcher for Xodus on Linux
TypeScript
Coalesce Store queries and bound cached search results
domsvobodadb67f05b3457
diff --git a/src/main/catalog-cache.test.ts b/src/main/catalog-cache.test.tsnew file mode 100644index 0000000..a7fc1d7--- /dev/null+++ b/src/main/catalog-cache.test.ts@@ -0,0 +1,90 @@+import { afterEach, expect, it, vi } from 'vitest';+import { CatalogService } from './catalog.js';++afterEach(() => vi.restoreAllMocks());+const response = () => new Response(JSON.stringify({ productsList: [], title: 'Featured' }), { status: 200 });+function barrier() {+ let release!: () => void;+ const promise = new Promise<void>(resolve => { release = resolve; });+ return { promise, release };+}++it.each(['search', 'featured'] as const)('coalesces twenty concurrent %s requests and isolates every caller result', async kind => {+ const gate = barrier();+ const fetcher = vi.fn(async () => { await gate.promise; return response(); });+ const catalog = new CatalogService(fetcher);+ const request = () => kind === 'search' ? catalog.search('Game', 'US') : catalog.featured('US');+ const pending = Array.from({ length: 20 }, request);+ await Promise.resolve();+ expect(fetcher).toHaveBeenCalledTimes(1);+ gate.release();+ const results = await Promise.all(pending);+ results[0].query = 'changed';+ results[0].products.length = 1;+ for (const result of results.slice(1)) {+ expect(result.query).not.toBe('changed');+ expect(result.products).toEqual([]);+ }+ expect((await request()).products).toEqual([]);+ expect(fetcher).toHaveBeenCalledTimes(1);+});++it('shares a failure without caching it and permits a clean retry', async () => {+ const gate = barrier();+ const fetcher = vi.fn(async () => { await gate.promise; return new Response('', { status: 503 }); });+ const catalog = new CatalogService(fetcher);+ const results = Promise.allSettled(Array.from({ length: 20 }, () => catalog.search('Game', 'US')));+ gate.release();+ for (const result of await results) {+ expect(result.status).toBe('rejected');+ if (result.status === 'rejected') expect(result.reason.message).toContain('503');+ }+ expect(fetcher).toHaveBeenCalledTimes(1);+ fetcher.mockImplementation(async () => response());+ expect((await catalog.search('Game', 'US')).products).toEqual([]);+ expect(fetcher).toHaveBeenCalledTimes(2);+});++it('separates markets, pages and featured results while retaining normalized search keys', async () => {+ const fetcher = vi.fn(async () => response());+ const catalog = new CatalogService(fetcher);+ await Promise.all([+ catalog.search('Game', 'US'), catalog.search(' game ', 'us'), catalog.search('Game', 'CZ'),+ catalog.search('Game', 'US', 'page2'), catalog.featured('US'), catalog.search('featured', 'US'),+ ]);+ expect(fetcher).toHaveBeenCalledTimes(5);+});++it('evicts least-recently-used results and expires entries without extending their lifetime on hits', async () => {+ let now = 1_800_000_000_000;+ vi.spyOn(Date, 'now').mockImplementation(() => now);+ const fetcher = vi.fn(async () => response());+ const catalog = new CatalogService(fetcher);+ for (let i = 0; i < 100; i++) await catalog.search(`game${i}`, 'US');+ now += 60_000;+ await catalog.search('game0', 'US');+ await catalog.search('extra', 'US');+ await catalog.search('game0', 'US');+ expect(fetcher).toHaveBeenCalledTimes(101);+ await catalog.search('game1', 'US');+ expect(fetcher).toHaveBeenCalledTimes(102);+ now += 540_000;+ await catalog.search('game0', 'US');+ expect(fetcher).toHaveBeenCalledTimes(103);+ await catalog.search('extra', 'US');+ expect(fetcher).toHaveBeenCalledTimes(103);+});++it('bounds outstanding distinct requests, allows joining a full queue and releases capacity after completion', async () => {+ const gate = barrier();+ const fetcher = vi.fn(async () => { await gate.promise; return response(); });+ const catalog = new CatalogService(fetcher);+ const requests = Array.from({ length: 32 }, (_, i) => catalog.search(`game${i}`, 'US'));+ const joined = catalog.search('game0', 'US');+ await expect(catalog.search('overflow', 'US')).rejects.toThrow('Too many Store requests');+ expect(fetcher).toHaveBeenCalledTimes(32);+ gate.release();+ await Promise.all([...requests, joined]);+ await catalog.search('overflow', 'US');+ expect(fetcher).toHaveBeenCalledTimes(33);+});diff --git a/src/main/catalog.ts b/src/main/catalog.tsindex c4fa4df..ea619a8 100644--- a/src/main/catalog.ts+++ b/src/main/catalog.ts@@ -57,6 +57,8 @@ interface BundleReference {const IMAGE_HOSTS = new Set(['store-images.s-microsoft.com', 'store-images.microsoft.com']);const STORE_HOSTS = new Set(['www.xbox.com', 'xbox.com', 'apps.microsoft.com']);const CACHE_TTL_MS = 10 * 60 * 1000;+const SEARCH_CACHE_LIMIT = 100;+const SEARCH_REQUEST_LIMIT = 32;// Box art is square and carries the game's title branding, matching the// square library tiles; promotional square art is the textless fallback.const POSTER_PURPOSES = ['BoxArt', 'TitledPoster', 'Poster', 'FeaturePromotionalSquareArt'];@@ -278,9 +280,34 @@ export class CatalogService {private readonly gameCache = new Map<string, { until: number; value: GameStoreDetails }>();private readonly gameRequests = new Map<string,Promise<GameStoreDetails|undefined>>();private readonly cache = new Map<string, { expires: number; value: CatalogSearchResult }>();+ private readonly requests = new Map<string, Promise<CatalogSearchResult>>();constructor(private readonly fetcher: Fetcher = fetch) {}+ private async cachedResult(key: string, load: () => Promise<CatalogSearchResult>): Promise<CatalogSearchResult> {+ const now = Date.now();+ for (const [entryKey, entry] of this.cache) if (entry.expires <= now) this.cache.delete(entryKey);+ const cached = this.cache.get(key);+ if (cached) {+ this.cache.delete(key);+ this.cache.set(key, cached);+ return structuredClone(cached.value);+ }+ const pending = this.requests.get(key);+ if (pending) return structuredClone(await pending);+ if (this.requests.size >= SEARCH_REQUEST_LIMIT) throw new Error('Too many Store requests. Try again.');+ const request = Promise.resolve().then(load);+ this.requests.set(key, request);+ try {+ const value = await request;+ while (this.cache.size >= SEARCH_CACHE_LIMIT) this.cache.delete(this.cache.keys().next().value!);+ this.cache.set(key, { expires: Date.now() + CACHE_TTL_MS, value });+ return structuredClone(value);+ } finally {+ this.requests.delete(key);+ }+ }+/** Read descriptive data independently of installation, ownership or package support. */async gameDetails(productId: string, rawMarket: string): Promise<GameStoreDetails | undefined> {if (!/^[A-Z0-9]{12}$/.test(productId)) throw Error('Invalid Store product ID.');@@ -445,9 +472,10 @@ export class CatalogService {if (cursor && (cursor.length > 4096 || !/^[A-Za-z0-9+/=_-]+$/.test(cursor))) throw new Error('The Store paging cursor is invalid.');const market = normalizeMarket(rawMarket);const cacheKey = `${market}\u0000${query.toLowerCase()}\u0000${cursor ?? ''}`;- const cached = this.cache.get(cacheKey);- if (cached && cached.expires > Date.now()) return structuredClone(cached.value);+ return this.cachedResult(cacheKey, () => this.searchResult(query, market, cursor));+ }+ private async searchResult(query: string, market: string, cursor?: string): Promise<CatalogSearchResult> {const searchUrl = new URL('https://apps.microsoft.com/api/products/search');for (const [key, value] of Object.entries({ query, mediaType: 'games', age: 'all', price: 'all', category: 'all', subscription: 'all', gl: market, hl: 'en-us' })) {searchUrl.searchParams.set(key, value);@@ -456,16 +484,16 @@ export class CatalogService {const searchResponse = await this.fetcher(searchUrl, { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(20_000) });if (!searchResponse.ok) throw new Error(`Microsoft Store search returned HTTP ${searchResponse.status}.`);const search = await searchResponse.json() as StoreSearchResponse;- const value = await this.result(search, query, market, true);- this.cache.set(cacheKey, { expires: Date.now() + CACHE_TTL_MS, value });- return structuredClone(value);+ return this.result(search, query, market, true);}async featured(rawMarket: string): Promise<CatalogSearchResult> {const market = normalizeMarket(rawMarket);const cacheKey = `${market}\u0000featured`;- const cached = this.cache.get(cacheKey);- if (cached && cached.expires > Date.now()) return structuredClone(cached.value);+ return this.cachedResult(cacheKey, () => this.featuredResult(market));+ }++ private async featuredResult(market: string): Promise<CatalogSearchResult> {const url = new URL('https://apps.microsoft.com/api/Reco/GetComputedProductsList');for (const [key, value] of Object.entries({listName: 'TopTrending', pgNo: '1', noItems: '12', filteredCategories: 'AllProducts',@@ -474,9 +502,7 @@ export class CatalogService {const response = await this.fetcher(url, { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(20_000) });if (!response.ok) throw new Error(`Microsoft Store featured collection returned HTTP ${response.status}.`);const search = await response.json() as StoreSearchResponse & { title?: unknown };- const value = await this.result(search, string(search.title) ?? 'Trending games', market, false);- this.cache.set(cacheKey, { expires: Date.now() + CACHE_TTL_MS, value });- return structuredClone(value);+ return this.result(search, string(search.title) ?? 'Trending games', market, false);}async posters(ids: string[], rawMarket: string): Promise<Map<string, string>> {