revert(media): remove browser media concurrency cap

This commit is contained in:
Erwan Leboucher committed 2026-08-13 20:39:46 +02:00
1 parent ca531ebabe
commit 3dfda4869b
4 files changed
+18 -123

No files matched your search

-71
View File
@@ -1,71 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
import { withMediaFetchSlot } from './mediaConcurrency';
describe('withMediaFetchSlot', () => {
it('never runs more than three tasks at once and runs all of them', async () => {
let active = 0;
let peak = 0;
const release: (() => void)[] = [];
const tasks = Array.from({ length: 10 }, () =>
withMediaFetchSlot(async () => {
active += 1;
peak = Math.max(peak, active);
await new Promise<void>((resolve) => {
release.push(resolve);
});
active -= 1;
})
);
while (release.length > 0) {
release.shift()?.();
// Let the freed slot reach the next waiter before draining again.
// eslint-disable-next-line no-await-in-loop
await new Promise((resolve) => {
setTimeout(resolve, 0);
});
}
await Promise.all(tasks);
expect(peak).toBe(3);
});
it('serves the newest waiter first so late requests are not stuck behind a backlog', async () => {
const started: number[] = [];
const release: (() => void)[] = [];
const enqueue = (id: number) =>
withMediaFetchSlot(async () => {
started.push(id);
await new Promise<void>((resolve) => {
release.push(resolve);
});
});
// 0-2 take the three slots; 3-5 are the backlog; 6 is the request the user just made.
const tasks = [0, 1, 2, 3, 4, 5, 6].map(enqueue);
await Promise.resolve();
expect(started).toEqual([0, 1, 2]);
release.shift()?.();
await vi.waitFor(() => expect(started).toHaveLength(4));
expect(started[3]).toBe(6);
while (release.length > 0) {
release.shift()?.();
// eslint-disable-next-line no-await-in-loop
await new Promise((resolve) => {
setTimeout(resolve, 0);
});
}
await Promise.all(tasks);
});
it('releases the slot when a task rejects', async () => {
await expect(withMediaFetchSlot(() => Promise.reject(new Error('boom')))).rejects.toThrow(
'boom'
);
await expect(withMediaFetchSlot(() => Promise.resolve('ok'))).resolves.toBe('ok');
});
});
-27
View File
@@ -1,27 +0,0 @@
// Media shares its host with the Matrix API, and browsers cap connections per host at 6.
// Leave slots free so a wave of media loads cannot queue /sync and /send behind it.
const MAX_CONCURRENT_MEDIA_FETCHES = 3;
const waiters: (() => void)[] = [];
let active = 0;
export async function withMediaFetchSlot<T>(task: () => Promise<T>): Promise<T> {
if (active < MAX_CONCURRENT_MEDIA_FETCHES) {
active += 1;
} else {
await new Promise<void>((resolve) => {
waiters.push(resolve);
});
}
try {
return await task();
} finally {
// Hand the slot straight to the next waiter instead of releasing and re-acquiring it.
// Newest first: a picker opened over a loading member list would otherwise wait
// behind every one of its avatars.
const next = waiters.pop();
if (next) next();
else active -= 1;
}
}
+13 -18
View File
@@ -1,7 +1,6 @@
import { getCachedSWMediaAuthSupport } from './swMediaAuth';
import { fetch } from '$utils/fetch';
import { getFromMediaCache, putInMediaCache } from './mediaCache';
import { withMediaFetchSlot } from './mediaConcurrency';
type StoredSession = {
baseUrl?: string;
@@ -327,9 +326,7 @@ async function fetchMediaBlobInternal(url: string, options?: MediaTransportOptio
};
if (useServiceWorker) {
return withMediaFetchSlot(async () =>
fetchAndCache(await fetchMediaResponse(url, undefined, cacheMode))
);
return fetchAndCache(await fetchMediaResponse(url, undefined, cacheMode));
}
const fetchWithRetry = async (
@@ -355,22 +352,20 @@ async function fetchMediaBlobInternal(url: string, options?: MediaTransportOptio
}
};
return withMediaFetchSlot(async () => {
const initialAccessToken = resolveAccessToken(url, options);
const initialResponse = await fetchWithRetry(url, initialAccessToken, cacheMode);
if (initialResponse.ok) {
return fetchAndCache(initialResponse);
}
const initialAccessToken = resolveAccessToken(url, options);
const initialResponse = await fetchWithRetry(url, initialAccessToken, cacheMode);
if (initialResponse.ok) {
return fetchAndCache(initialResponse);
}
if (!isRetryableAuthError(initialResponse)) {
throw new Error(
`Failed to fetch media: ${initialResponse.status} ${initialResponse.statusText}`
);
}
if (!isRetryableAuthError(initialResponse)) {
throw new Error(
`Failed to fetch media: ${initialResponse.status} ${initialResponse.statusText}`
);
}
const retryAccessToken = resolveAccessToken(url, options);
return fetchAndCache(await fetchMediaResponse(url, retryAccessToken, cacheMode));
});
const retryAccessToken = resolveAccessToken(url, options);
return fetchAndCache(await fetchMediaResponse(url, retryAccessToken, cacheMode));
}
export async function fetchMediaBlob(url: string, options?: MediaTransportOptions): Promise<Blob> {
+5 -7
View File
@@ -5,7 +5,6 @@ import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
import { EventType } from 'matrix-js-sdk/lib/@types/event';
import { createPushNotifications } from './sw/pushNotification';
import { withMediaFetchSlot } from './app/utils/mediaConcurrency';
import { readPersistedSession } from './sw-session-persistence';
declare const self: ServiceWorkerGlobalScope;
@@ -810,9 +809,8 @@ function respondWithInflightMedia(
// Fetch by URL instead of reusing the subresource Request. Image requests commonly carry
// mode: "no-cors", which prevents the Authorization header above from reaching the server.
// Preserve Range header for streaming audio and video.
// The slot is held until the body has been read, since that is what holds the connection.
const promise = withMediaFetchSlot(() =>
fetch(request.url, { ...fetchConfig(token, request), redirect }).then(
const promise = fetch(request.url, { ...fetchConfig(token, request), redirect })
.then(
async (res): Promise<BufferedMediaResponse> => ({
status: res.status,
statusText: res.statusText,
@@ -820,9 +818,9 @@ function respondWithInflightMedia(
body: await res.arrayBuffer(),
})
)
).finally(() => {
inflightMediaFetches.delete(key);
});
.finally(() => {
inflightMediaFetches.delete(key);
});
inflightMediaFetches.set(key, promise);
return promise.then(
(data) =>