Spaces:
Sleeping
Sleeping
File size: 2,997 Bytes
1305386 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | import { Dropbox } from "dropbox";
import { StorageType } from "../../types/StorageType";
import { IPayloadReference } from "../../interfaces/core/IPayloadReference";
import { IStoragePoster } from "../../interfaces/core/IStoragePoster";
export class DropboxPoster implements IStoragePoster {
storageType: StorageType = "dropbox";
private readonly MAX_RETRIES = 3;
private readonly RETRY_DELAY_BASE = 5000; // 5 seconds base delay
constructor() {}
async post(reference: IPayloadReference): Promise<IPayloadReference> {
const apiToken: string = reference.apiToken!;
let data: Buffer | string = reference.data || "";
let dropboxPath: string = reference.filePath || "/snake/default.txt";
if (!apiToken) throw new Error("Dropbox API token is required");
// Convert string to Buffer if needed
const uploadData = typeof data === 'string' ? Buffer.from(data, 'utf-8') : data;
const dbx = new Dropbox({ accessToken: apiToken });
let lastError: Error | null = null;
// Retry mechanism with exponential backoff
for (let attempt = 1; attempt <= this.MAX_RETRIES; attempt++) {
try {
console.log(`[DropboxPoster] Uploading file to Dropbox (attempt ${attempt}/${this.MAX_RETRIES}): ${dropboxPath}`);
let response = await dbx.filesUpload({
path: dropboxPath,
contents: uploadData,
mode: { ".tag": "overwrite" },
});
console.log(`[DropboxPoster] File uploaded successfully to Dropbox:`, response.result.name);
return {
...reference,
filePath: dropboxPath,
data: uploadData
};
} catch (error) {
lastError = error as Error;
console.error(`[DropboxPoster] Upload attempt ${attempt}/${this.MAX_RETRIES} failed:`, lastError.message);
// If this is not the last attempt, wait before retrying
if (attempt < this.MAX_RETRIES) {
const delayMs = this.RETRY_DELAY_BASE * Math.pow(2, attempt - 1); // Exponential backoff
console.log(`[DropboxPoster] Retrying in ${delayMs}ms...`);
await this.delay(delayMs);
}
}
}
// All retries exhausted, throw the last error
console.error(`[DropboxPoster] All ${this.MAX_RETRIES} upload attempts failed for: ${dropboxPath}`);
throw new Error(`Failed to upload file to Dropbox after ${this.MAX_RETRIES} attempts: ${lastError?.message || 'Unknown error'}`);
}
private delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
} |