web/workers/fetch: retry 5 more times before throwing an error

hopium

should probably add a timeout too
This commit is contained in:
wukko 2025-03-06 14:30:52 +06:00
parent 066a47c82d
commit 9225b31986
No known key found for this signature in database
GPG Key ID: 3E30B3F26C7B4AA2

View File

@ -1,21 +1,34 @@
import { OPFSStorage } from "$lib/storage";
const error = (code: string) => {
// TODO: return proper errors and code here
self.postMessage({
cobaltFetchWorker: {
error: code,
}
})
};
let attempts = 0;
const fetchFile = async (url: string) => {
const error = async (code: string) => {
attempts++;
if (attempts <= 5) {
// try 5 more times before actually failing
console.log("fetch attempt", attempts);
await fetchFile(url);
} else {
// if it still fails, then throw an error and quit
self.postMessage({
cobaltFetchWorker: {
// TODO: return proper error code here
// (error.code and not just random shit i typed up)
error: code,
}
});
self.close();
}
};
try {
const response = await fetch(url);
if (!response.ok) {
error("file response wasn't ok");
return self.close();
return error("file response wasn't ok");
}
const contentType = response.headers.get('Content-Type') || 'application/octet-stream';
@ -27,8 +40,7 @@ const fetchFile = async (url: string) => {
const storage = await OPFSStorage.init();
if (!reader) {
error("no reader");
return self.close();
return error("no reader");
}
let receivedBytes = 0;
@ -51,14 +63,13 @@ const fetchFile = async (url: string) => {
}
if (receivedBytes === 0) {
error("tunnel is broken");
return self.close();
return error("tunnel is broken");
}
const file = await storage.res();
if (Number(contentLength) !== file.size) {
error("file is not downloaded fully");
return error("file was not downloaded fully");
}
self.postMessage({
@ -71,8 +82,7 @@ const fetchFile = async (url: string) => {
});
} catch (e) {
console.log(e);
error("error when downloading the file");
return self.close();
return error("error when downloading the file");
}
}