Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 16 additions & 12 deletions src/utils/data/storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,14 @@ const hasFetched = () => {
return false;
}

// Every file and the media probe must be in. Counting the stored keys is not
// enough: the media probe is stored in the same object, so the count could
// reach the number of files with one of them still missing
const hasLoaded = () => {
const stored = Object.keys(DATA).length;
const data = Object.keys(files).length;
const filesLoaded = Object.keys(files).every(data => Object.hasOwn(DATA, data));
const mediaLoaded = Object.hasOwn(DATA, ID.MEDIA);

if (stored >= data) {
if (filesLoaded && mediaLoaded) {
logger.debug(ID.STORAGE, STATE.LOADED);
STATUS = STATE.LOADED;

Expand Down Expand Up @@ -94,18 +97,16 @@ const fetchFile = (data, recordId, onUpdate, onLoaded, onError) => {
const fetchMedia = (recordId, onUpdate, onLoaded, onError) => {
const fetches = medias.map(type => {
const url = buildFileURL(`video/webcams.${type}`, recordId);
return fetch(url, { method: 'HEAD' });
// A probe failing at the network level must not discard the other formats
return fetch(url, { method: 'HEAD' }).catch(error => {
logger.warn(ID.STORAGE, ID.MEDIA, type, error);
return null;
});
});

Promise.all(fetches).then(responses => {
const media = [];
responses.forEach(response => {
const { ok, url } = response;
if (ok) {
logger.debug(ID.STORAGE, ID.MEDIA, response);
media.push(medias.find(type => url.endsWith(type)));
}
});
const media = medias.filter((type, index) => responses[index]?.ok);
logger.debug(ID.STORAGE, ID.MEDIA, media);

if (media.length > 0) {
DATA[ID.MEDIA] = media;
Expand Down Expand Up @@ -134,6 +135,9 @@ const tryMediaFallback = (recordId, onUpdate, onLoaded, onError) => {
} else {
onError(ERROR.NOT_FOUND);
}
}).catch(error => {
logger.warn(ID.STORAGE, ID.MEDIA, error);
onError(ERROR.NOT_FOUND);
});
};

Expand Down
120 changes: 120 additions & 0 deletions src/utils/data/storage.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { files } from 'config';
import { ERROR } from 'utils/constants';

const MISSING = { ok: false, status: 404 };

// Fresh storage module per test: it keeps the fetched data in module state
const loadStorage = () => {
let storage;
jest.isolateModules(() => {
storage = require('./storage').default;
});

return storage;
};

// fetch mock where each response is released by hand, in any order
const deferredFetch = () => {
const pending = {};
global.fetch = jest.fn((url, options = {}) => new Promise((resolve, reject) => {
const key = `${options.method || 'GET'} ${url.split('/').slice(-2).join('/')}`;
pending[key] = { resolve, reject };
}));

return pending;
};

const flush = () => new Promise(resolve => setTimeout(resolve, 0));

const fileKey = (file) => `GET rec/${file}`;

describe('storage', () => {
afterEach(() => {
delete global.fetch;
});

it('waits for the last file after the media probe', async () => {
const pending = deferredFetch();
const storage = loadStorage();
const onLoaded = jest.fn();
storage.fetch('rec', jest.fn(), onLoaded, jest.fn());

const names = Object.values(files);
const last = names.pop();
names.forEach(file => pending[fileKey(file)].resolve(MISSING));
pending['HEAD video/webcams.mp4'].resolve({ ok: true, url: 'rec/video/webcams.mp4' });
pending['HEAD video/webcams.webm'].resolve(MISSING);
await flush();

expect(onLoaded).not.toHaveBeenCalled();

pending[fileKey(last)].resolve(MISSING);
await flush();

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

it('waits for the media probe after the last file', async () => {
const pending = deferredFetch();
const storage = loadStorage();
const onLoaded = jest.fn();
storage.fetch('rec', jest.fn(), onLoaded, jest.fn());

Object.values(files).forEach(file => pending[fileKey(file)].resolve(MISSING));
await flush();

expect(onLoaded).not.toHaveBeenCalled();

pending['HEAD video/webcams.mp4'].resolve({ ok: true, url: 'rec/video/webcams.mp4' });
pending['HEAD video/webcams.webm'].resolve(MISSING);
await flush();

expect(onLoaded).toHaveBeenCalledTimes(1);
expect(storage.media).toEqual(['mp4']);
});

it('keeps the format of a redirected probe', async () => {
const pending = deferredFetch();
const storage = loadStorage();
storage.fetch('rec', jest.fn(), jest.fn(), jest.fn());

Object.values(files).forEach(file => pending[fileKey(file)].resolve(MISSING));
pending['HEAD video/webcams.mp4'].resolve({ ok: true, url: 'https://cdn/webcams.mp4?signature=x' });
pending['HEAD video/webcams.webm'].resolve(MISSING);
await flush();

expect(storage.media).toEqual(['mp4']);
});

it('keeps the formats whose probe did not fail', async () => {
const pending = deferredFetch();
const storage = loadStorage();
const onLoaded = jest.fn();
const onError = jest.fn();
storage.fetch('rec', jest.fn(), onLoaded, onError);

Object.values(files).forEach(file => pending[fileKey(file)].resolve(MISSING));
pending['HEAD video/webcams.mp4'].resolve({ ok: true, url: 'rec/video/webcams.mp4' });
pending['HEAD video/webcams.webm'].reject(new TypeError('Failed to fetch'));
await flush();

expect(onError).not.toHaveBeenCalled();
expect(onLoaded).toHaveBeenCalledTimes(1);
expect(storage.media).toEqual(['mp4']);
});

it('reports an error when every media probe fails', async () => {
const pending = deferredFetch();
const storage = loadStorage();
const onError = jest.fn();
storage.fetch('rec', jest.fn(), jest.fn(), onError);

pending['HEAD video/webcams.mp4'].reject(new TypeError('Failed to fetch'));
pending['HEAD video/webcams.webm'].reject(new TypeError('Failed to fetch'));
await flush();
pending['HEAD audio/audio.webm'].reject(new TypeError('Failed to fetch'));
await flush();

expect(onError).toHaveBeenCalledWith(ERROR.NOT_FOUND);
});
});