fix: stop federated search from freezing the player
Build and Publish / Build and Publish Docker Image (push) Successful in 2m35s
Build and Publish / Build and Publish Docker Image (push) Successful in 2m35s
This commit is contained in:
1 parent
62f28066b3
commit
0394d40b75
8 files changed
+317
-193
No files matched your search
@@ -0,0 +1,153 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
|
||||
const html = fs.readFileSync('target/podcast-player-fixture.html', 'utf8');
|
||||
const alpine = fs.readFileSync('target/podcast-alpine.min.js', 'utf8');
|
||||
function stream(events) {
|
||||
return events.map(([kind, entity], index) => {
|
||||
const data = JSON.stringify({ kind, sequence: index + 1, entity });
|
||||
return `event: ${kind}\ndata: ${data}\n\n`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function track(id, title) {
|
||||
return {
|
||||
key: { content_id: `b3:${String(id).padStart(64, '0')}` },
|
||||
metadata: { title, artists: [{ name: 'Band' }], duration_seconds: 180 + id },
|
||||
availability: { state: 'federated', federation: [{ owner: 'peer', item_id: String(id) }] },
|
||||
};
|
||||
}
|
||||
|
||||
const trackCount = 120;
|
||||
const groupCount = 6;
|
||||
const burst = stream([
|
||||
...Array.from({ length: trackCount }, (_, id) => ['federation.track', track(id, 'Song ' + (id % groupCount))]),
|
||||
['federation.artist', { key: { normalized_name: 'band' }, name: 'Band', peers: ['peer'] }],
|
||||
['federation.release', {
|
||||
key: { normalized_title: 'album', primary_artists: ['band'], year: 2000 },
|
||||
title: 'Album', artists: ['Band'], year: 2000, cover_url: '/test/missing-cover', sources: [],
|
||||
}],
|
||||
['search.completed', { partial: false }],
|
||||
]);
|
||||
|
||||
(async () => {
|
||||
const browser = await chromium.launch({
|
||||
headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}),
|
||||
});
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 1200, height: 900 } });
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.EventSource = class extends EventSource {
|
||||
constructor(url, options) {
|
||||
super(url, options);
|
||||
if (url.startsWith('/api/player/federation/search/events?')) window.searchStream = this;
|
||||
}
|
||||
};
|
||||
});
|
||||
let sendBurst, sendOnLeave;
|
||||
const responses = new Map([
|
||||
['Song', new Promise(resolve => { sendBurst = resolve; })],
|
||||
['leave', new Promise(resolve => { sendOnLeave = resolve; })],
|
||||
['partial', stream([
|
||||
['federation.track', track(1, 'Other song')],
|
||||
['federation.track', track(2, 'Partial match')],
|
||||
['federation.track', track(3, 'Provisional title')],
|
||||
['federation.track', track(3, 'Partial')],
|
||||
['search.failed', { message: 'Peer disconnected' }],
|
||||
])],
|
||||
]);
|
||||
await page.route('**/*', async route => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.hostname === 'groups.test' && url.pathname === '/') {
|
||||
return route.fulfill({ contentType: 'text/html', body: html });
|
||||
}
|
||||
if (url.hostname === 'cdn.jsdelivr.net' && url.pathname.includes('alpine')) {
|
||||
return route.fulfill({ contentType: 'application/javascript', body: alpine });
|
||||
}
|
||||
if (url.pathname === '/api/player/search') {
|
||||
return route.fulfill({ json: { tracks: [], artists: [], releases: [], podcasts: [] } });
|
||||
}
|
||||
if (url.pathname === '/api/player/artists') {
|
||||
return route.fulfill({ json: { items: [], total: 0, has_more: false } });
|
||||
}
|
||||
if (url.pathname === '/api/player/federation/search/events') {
|
||||
const body = await responses.get(url.searchParams.get('q'));
|
||||
return route.fulfill({ contentType: 'text/event-stream', body });
|
||||
}
|
||||
if (url.pathname === '/test/local-artist') return route.fulfill({
|
||||
contentType: 'image/svg+xml', body: '<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>',
|
||||
});
|
||||
if (route.request().resourceType() === 'image') return route.fulfill({ status: 404, body: '' });
|
||||
return route.fulfill({ json: [] });
|
||||
});
|
||||
await page.goto('http://groups.test/');
|
||||
await page.waitForFunction(() => window.Alpine?.store('library'));
|
||||
await page.evaluate(async () => {
|
||||
const library = Alpine.store('library');
|
||||
window.imageErrors = 0;
|
||||
document.addEventListener('error', event => {
|
||||
if (event.target instanceof HTMLImageElement && event.target.closest('.federation-entity-card')) {
|
||||
window.imageErrors++;
|
||||
}
|
||||
}, true);
|
||||
library.searchQuery = 'Song';
|
||||
await library.search('Song');
|
||||
window.trackUpdates = 0;
|
||||
Alpine.effect(() => {
|
||||
void library.federationSearch.tracks;
|
||||
window.trackUpdates++;
|
||||
});
|
||||
window.started = performance.now();
|
||||
});
|
||||
sendBurst(burst);
|
||||
await page.waitForFunction(() => !Alpine.store('library').federationSearch.loading);
|
||||
const first = await page.evaluate(() => ({
|
||||
elapsed: Math.round(performance.now() - window.started),
|
||||
updates: window.trackUpdates,
|
||||
sourceTracks: Alpine.store('library').federationSearch.tracks.length,
|
||||
mountedRows: document.querySelectorAll('[data-search-source="federation"]').length,
|
||||
}));
|
||||
await page.waitForFunction(() => window.imageErrors >= 3);
|
||||
// Allow several turns of the event loop after the last valid fallback has failed.
|
||||
await page.waitForTimeout(400);
|
||||
const final = await page.evaluate(() => ({ errors: window.imageErrors, updates: window.trackUpdates }));
|
||||
console.log('Federation search burst', { ...first, imageErrors: final.errors, settledUpdates: final.updates });
|
||||
assert.equal(first.sourceTracks, trackCount);
|
||||
assert.equal(first.mountedRows, groupCount);
|
||||
assert.equal(await page.locator('.federation-entity-card img').count(), 0);
|
||||
assert.equal(final.errors, 3, 'each of the three missing artwork URLs is tried once');
|
||||
assert.ok(first.updates < trackCount / 2, 'the event stream is published in batches');
|
||||
assert.equal(final.updates, first.updates, 'artwork failures do not invalidate track results');
|
||||
|
||||
// A local image arriving after the missing federation image still gets a chance to load.
|
||||
await page.evaluate(() => {
|
||||
Alpine.store('library').searchResults.artists = [{ id: 1, name: 'Band', image_url: '/test/local-artist' }];
|
||||
});
|
||||
await page.waitForSelector('.federation-entity-card img.artwork-loaded[src="/test/local-artist"]');
|
||||
|
||||
// A failing stream publishes its last batch, including replacements for existing content IDs.
|
||||
await page.evaluate(() => Alpine.store('library').search('partial'));
|
||||
await page.waitForFunction(() => Alpine.store('library').federationSearch.error === 'Peer disconnected');
|
||||
assert.deepEqual(await page.locator('[data-search-source="federation"] .search-track-name').allTextContents(),
|
||||
['Partial', 'Partial match', 'Other song']);
|
||||
|
||||
// Leave after the first SSE event has been buffered but before its batch is published.
|
||||
await page.evaluate(async () => {
|
||||
const library = Alpine.store('library');
|
||||
await library.search('leave');
|
||||
window.searchStream.addEventListener('federation.track', () => library.goArtists(), { once: true });
|
||||
});
|
||||
sendOnLeave(burst);
|
||||
await page.waitForFunction(() => Alpine.store('library').view === 'artists');
|
||||
await page.waitForTimeout(100);
|
||||
assert.equal(await page.evaluate(() => window.searchStream.readyState === EventSource.CLOSED), true);
|
||||
assert.deepEqual(await page.evaluate(() => Alpine.store('library').federationSearch),
|
||||
{ loading: false, error: '', artists: [], releases: [], tracks: [] });
|
||||
assert.deepEqual(errors, []);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
@@ -11,12 +11,15 @@ const near=(a,b,message)=>assert.ok(Math.abs(a-b)<1,`${message}: ${a} vs ${b}`);
|
||||
const u=new URL(route.request().url());
|
||||
if(u.hostname==='search.test'&&u.pathname==='/')return route.fulfill({contentType:'text/html',body:html});
|
||||
if(u.hostname==='cdn.jsdelivr.net'&&u.pathname.includes('alpine'))return route.fulfill({contentType:'application/javascript',body:alpine});
|
||||
if(u.pathname==='/api/player/me')return route.fulfill({json:{name:'Listener'}});
|
||||
if(u.pathname==='/api/player/artists')return route.fulfill({json:{items:[],total:0,has_more:false}});
|
||||
if(u.pathname==='/api/player/search')return route.fulfill({json:{artists:[],releases:[],tracks:[],podcasts:[]}});
|
||||
return route.fulfill({json:[]});
|
||||
});
|
||||
await page.goto('http://search.test/');await page.waitForFunction(()=>window.Alpine?.store('library'));
|
||||
await page.goto('http://search.test/');await page.waitForFunction(()=>window.Alpine?.store('user')?.profile?.name==='Listener');
|
||||
const input=page.locator('#search-input'),panel=page.locator('.content-topbar');
|
||||
const account=page.locator('.mobile-account-chip');
|
||||
if(width<=560)await account.waitFor({state:'visible'});
|
||||
const original=await input.boundingBox(),panelBefore=await panel.boundingBox(),buttonBefore=await page.locator('.torrent-import-btn').boundingBox();
|
||||
await input.focus();
|
||||
if(width<=560){
|
||||
@@ -26,8 +29,10 @@ const near=(a,b,message)=>assert.ok(Math.abs(a-b)<1,`${message}: ${a} vs ${b}`);
|
||||
// Account data may arrive after the user has already focused the input.
|
||||
// Changing header controls must not shrink the expanded search again.
|
||||
await page.evaluate(()=>Alpine.store('user').profile=null);
|
||||
await account.waitFor({state:'hidden'});
|
||||
await page.waitForFunction(()=>{const input=document.querySelector('#search-input').getBoundingClientRect(),panel=document.querySelector('.content-topbar').getBoundingClientRect();return Math.abs(input.width-panel.width)<1;});
|
||||
await page.evaluate(()=>Alpine.store('user').profile={name:'Listener'});
|
||||
await account.waitFor({state:'visible'});
|
||||
await page.waitForFunction(()=>{const input=document.querySelector('#search-input').getBoundingClientRect(),panel=document.querySelector('.content-topbar').getBoundingClientRect();return Math.abs(input.width-panel.width)<1;});
|
||||
const topmost=await page.evaluate(()=>{const panel=document.querySelector('.content-topbar').getBoundingClientRect();return document.elementFromPoint(panel.right-10,panel.top+panel.height/2)?.id;});
|
||||
assert.equal(topmost,'search-input','search overlays account and download controls');
|
||||
|
||||
@@ -25,17 +25,16 @@ const data={local:[local(1),local(2,'Another song'),local(3),local(4,'Still Lovi
|
||||
library.playFederatedTrack=track=>window.groupPlays.push({source:'federation',id:track.key.content_id});
|
||||
},data);
|
||||
const localRows=page.locator('[data-search-source="local"]'),remoteRows=page.locator('[data-search-source="federation"]');
|
||||
await page.waitForFunction(()=>document.querySelectorAll('[data-search-source="local"]').length===5);
|
||||
assert.equal(await localRows.count(),5);assert.equal(await remoteRows.count(),3);
|
||||
await page.waitForFunction(()=>document.querySelectorAll('[data-search-source="local"]').length===3);
|
||||
assert.equal(await localRows.count(),3);assert.equal(await remoteRows.count(),2);
|
||||
assert.equal(await localRows.locator('.search-version-toggle:visible').count(),1);
|
||||
assert.equal(await localRows.nth(1).getAttribute('inert')!==null,true);
|
||||
assert.ok((await localRows.nth(1).boundingBox()).height<1);assert.ok((await localRows.nth(2).boundingBox()).height<1);
|
||||
assert.equal(await localRows.locator('.search-track-variant').count(),0,'collapsed versions are unmounted');
|
||||
assert.equal(await localRows.first().locator('.search-version-toggle').getAttribute('aria-expanded'),'false');
|
||||
await localRows.first().locator('.search-track-name').click();
|
||||
assert.deepEqual(await page.evaluate(()=>window.groupPlays.at(-1)),{source:'local',ids:[1,2,4],id:1});
|
||||
await page.evaluate(()=>{window.groupPlays=[];window.groupNodes=[...document.querySelectorAll('[data-search-source="local"]')];});
|
||||
const animation=await page.evaluate(()=>new Promise(resolve=>{
|
||||
const head=document.querySelector('[data-search-source="local"]'),next=document.querySelectorAll('[data-search-source="local"]')[3],positions=[],start=performance.now();
|
||||
const [head,next]=window.groupNodes,positions=[],start=performance.now();
|
||||
head.querySelector('.search-version-toggle').click();
|
||||
function sample(){positions.push(next.getBoundingClientRect().top);if(performance.now()-start<230)requestAnimationFrame(sample);else resolve(positions);}
|
||||
requestAnimationFrame(sample);
|
||||
@@ -44,7 +43,8 @@ const data={local:[local(1),local(2,'Another song'),local(3),local(4,'Still Lovi
|
||||
assert.equal(await page.evaluate(()=>window.groupPlays.length),0,'branch toggle does not play');
|
||||
assert.equal(await localRows.first().locator('.search-version-toggle').getAttribute('aria-expanded'),'true');
|
||||
assert.equal(await localRows.nth(1).getAttribute('inert'),null);
|
||||
assert.equal(await page.evaluate(()=>window.groupNodes.every((node,index)=>node===document.querySelectorAll('[data-search-source="local"]')[index])),true,'stable DOM identities on toggle');
|
||||
assert.equal(await localRows.count(),5);
|
||||
assert.equal(await page.evaluate(()=>window.groupNodes.every(node=>document.getElementById(node.id)===node)),true,'representatives keep their DOM identities');
|
||||
for(let index=0;index<3;index++){
|
||||
const row=localRows.nth(index),box=await row.boundingBox(),actions=await row.locator('.track-actions').boundingBox();
|
||||
assert.ok(actions.x>=0&&actions.x+actions.width<=width,'actions fit viewport');assert.ok(actions.y>=box.y&&actions.y+actions.height<=box.y+box.height+1);
|
||||
@@ -56,13 +56,13 @@ const data={local:[local(1),local(2,'Another song'),local(3),local(4,'Still Lovi
|
||||
function sample(){positions.push(rows[3].getBoundingClientRect().top);if(performance.now()-start<230)requestAnimationFrame(sample);else resolve(positions);}requestAnimationFrame(sample);
|
||||
}));
|
||||
assert.ok(new Set(closing.map(y=>Math.round(y))).size>2,'collapse also moves siblings smoothly');
|
||||
await page.waitForFunction(()=>document.querySelectorAll('[data-search-source="local"]')[1].getBoundingClientRect().height<1);
|
||||
assert.equal(await localRows.nth(1).getAttribute('aria-hidden'),'true');
|
||||
await page.waitForFunction(()=>document.querySelectorAll('[data-search-source="local"]').length===3);
|
||||
assert.equal(await localRows.locator('.search-track-variant').count(),0);
|
||||
await localRows.first().locator('.search-version-toggle').focus();await page.keyboard.press('Enter');
|
||||
await page.waitForFunction(()=>document.querySelector('[data-search-source="local"] .search-version-toggle').getAttribute('aria-expanded')==='true');
|
||||
await page.evaluate(()=>new Promise(resolve=>{const button=document.querySelector('[data-search-source="local"] .search-version-toggle');[0,20,40,60,80].forEach(delay=>setTimeout(()=>button.click(),delay));setTimeout(resolve,280);}));
|
||||
assert.equal(await localRows.first().locator('.search-version-toggle').getAttribute('aria-expanded'),'false');
|
||||
assert.ok((await localRows.nth(1).boundingBox()).height<1,'rapid toggles settle in the final state');
|
||||
assert.equal(await localRows.count(),3,'rapid toggles settle in the final state');
|
||||
const remoteHead=remoteRows.first();await remoteHead.locator('.search-version-toggle').click();
|
||||
await page.evaluate(track=>Alpine.store('library').federationSearch.tracks.push(track),remote(14));
|
||||
await page.waitForFunction(()=>document.querySelectorAll('[data-search-source="federation"]').length===4);
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
const assert=require('node:assert/strict'),{test}=require('node:test'),fs=require('node:fs'),vm=require('node:vm');
|
||||
const script=fs.readFileSync(`${__dirname}/../templates/player/search_group_scripts.html`,'utf8').replace(/<\/?script>/g,'');
|
||||
function setup(){const stores={queue:{playRelease(tracks,index){this.tracks=tracks;this.index=index;}}};const context=vm.createContext({document:{documentElement:{lang:'en'},addEventListener(_,fn){fn();}},Alpine:{store(name,value){if(value)stores[name]=value;return stores[name];}}});vm.runInContext(script,context);return {groups:stores.searchGroups,stores,context};}
|
||||
function setup(){const stores={queue:{playRelease(tracks,index){this.tracks=tracks;this.index=index;}}};const context=vm.createContext({clearTimeout,setTimeout,window:{matchMedia:()=>({matches:false})},document:{documentElement:{lang:'en'},addEventListener(_,fn){fn();}},Alpine:{store(name,value){if(value)stores[name]=value;return stores[name];}}});vm.runInContext(script,context);return {groups:stores.searchGroups,stores,context};}
|
||||
const local=(id,title='Still Loving You',artist='Scorpions')=>({id,title,artists:[{id:1,name:artist}],release_title:'Album '+id});
|
||||
const ids=rows=>Array.from(rows,row=>row.id);
|
||||
test('groups nonadjacent titles by performer, preserving original indices and versions',()=>{
|
||||
const {groups}=setup(),tracks=[local(1),local(2,'Other'),local(3,' STILL LOVING YOU '),local(4,'Still Loving You','Someone else'),local(5,'Still Loving You (Live)')];
|
||||
const rows=groups.rows(tracks,'local');assert.deepEqual(ids(rows),[1,3,2,4,5]);assert.equal(rows[0]._searchGroupCount,2);assert.equal(rows[1]._searchGroupHidden,true);assert.equal(rows[1]._searchSourceIndex,2);
|
||||
assert.equal(rows[2]._searchGroupCount,1);assert.equal(rows[3]._searchGroupCount,1);assert.equal(rows[4]._searchGroupCount,1);assert.equal(tracks[0]._searchGroupKey,undefined);
|
||||
const rows=groups.rows(tracks,'local');assert.deepEqual(ids(rows),[1,2,4,5]);assert.equal(rows[0]._searchGroupCount,2);
|
||||
assert.ok(rows.slice(1).every(row=>row._searchGroupCount===1));assert.equal(tracks[0]._searchGroupKey,undefined);
|
||||
groups.toggle(rows[0]);const expanded=groups.rows(tracks,'local');
|
||||
assert.deepEqual(ids(expanded),[1,3,2,4,5]);assert.equal(expanded[1]._searchSourceIndex,2);
|
||||
});
|
||||
test('expansion survives streamed federation updates and resets for a new search',()=>{
|
||||
const {groups}=setup();const remote=id=>({key:{content_id:'b3:'+id},metadata:{title:'Song',artists:[{name:'Artist'}]},availability:{federation:[{owner:'peer',item_id:id}]}});
|
||||
let rows=groups.rows([remote(1),remote(2)],'federation');groups.toggle(rows[0]);
|
||||
rows=groups.rows([remote(1),remote(2),remote(3)],'federation');assert.equal(rows[0]._searchGroupCount,3);assert.ok(rows.every(row=>!row._searchGroupHidden));
|
||||
assert.equal(new Set(rows.map(row=>row._searchRowId)).size,3);assert.equal(rows[0]._searchGroupControls.split(' ').length,2);
|
||||
groups.reset();assert.equal(groups.rows([remote(1),remote(2)],'federation')[1]._searchGroupHidden,true);
|
||||
assert.ok(rows.slice(1).every(row=>row._searchGroupControls===null));
|
||||
groups.reset();assert.equal(groups.rows([remote(1),remote(2)],'federation').length,1);
|
||||
});
|
||||
test('audio similarity keeps its original ungrouped ranking',()=>{
|
||||
const {groups}=setup(),tracks=[local(1),local(2,'Other'),local(3)];const rows=groups.rows(tracks,'local',false);
|
||||
|
||||
Reference in new issue
Block a user