Skip to content

best way to save what you love

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

wukko9225b319865b
diff --git a/web/src/lib/workers/fetch.ts b/web/src/lib/workers/fetch.ts
index aa30a4c4..62d05206 100644
--- a/web/src/lib/workers/fetch.ts
+++ b/web/src/lib/workers/fetch.ts
@@ -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");
}
}