Skip to content

gitflarePublicPartly agent-ready50

cf-r2-drop

Drag-and-drop file sharing on Cloudflare R2: multipart uploads, expiring share links, previews, download counts, lifecycle expiry.

Serve the share page from the extensionless asset path0e4544f
JavaScript109 lines5.5 KB
// Upload engine. API: POST /api/uploads {name,size,type} -> {id,multipart,uploadId?,partSize?}// PUT /api/uploads/:id/parts/:n -> {etag}; POST /api/uploads/:id/complete {parts}; DELETE /api/uploads/:idexport const PART_SIZE = 8 * 1024 * 1024;export const MULTIPART_MIN = 10 * 1024 * 1024;export const CONCURRENCY = 4;export const RETRIES = 3; export function planParts(size, partSize = PART_SIZE) {  const out = [];  for (let s = 0, n = 1; s < size; s += partSize, n++) out.push({ n, start: s, end: Math.min(s + partSize, size) });  return out;}export const fmtBytes = (b) => {  if (!Number.isFinite(b)) return "–";  const u = ["B", "KB", "MB", "GB", "TB"]; let i = 0;  while (b >= 1000 && i < 4) { b /= 1000; i++; }  return `${i ? b.toFixed(b < 10 ? 2 : 1) : b} ${u[i]}`;};export const fmtEta = (s) => {  if (!Number.isFinite(s) || s < 0) return "–";  s = Math.round(s);  return s >= 3600 ? `${Math.floor(s / 3600)}h ${Math.floor(s % 3600 / 60)}m` : s >= 60 ? `${Math.floor(s / 60)}m ${s % 60}s` : `${s}s`;};export const fmtCountdown = (ms) => {  if (ms <= 0) return "expired";  const s = Math.floor(ms / 1000), d = Math.floor(s / 86400), h = Math.floor(s % 86400 / 3600), m = Math.floor(s % 3600 / 60);  return d ? `${d}d ${h}h` : h ? `${h}h ${m}m` : `${m}m ${s % 60}s`;}; const sleep = (ms) => new Promise((r) => setTimeout(r, ms));export async function withRetry(fn, { retries = RETRIES, base = 400, wait = sleep, signal } = {}) {  for (let a = 0; ; a++) {    try { return await fn(a); } catch (e) {      if (signal?.aborted || e.name === "AbortError" || a >= retries || e.fatal) throw e;      await wait(base * 2 ** a);    }  }} export class Uploader {  constructor(file, { fetch: f = globalThis.fetch.bind(globalThis), onProgress = () => {}, wait, now = Date.now } = {}) {    Object.assign(this, { file, f, onProgress, wait, now, state: "queued", loaded: 0, speed: 0, parts: [], done: new Map() });    this.partLoaded = new Map();  }  get multipart() { return this.file.size >= MULTIPART_MIN; }  emit() {    const t = this.now(), dt = (t - (this.last ?? t)) / 1000;    if (this.last && dt > 0.25) { this.speed = this.speed * 0.6 + ((this.loaded - this.lastLoaded) / dt) * 0.4; this.last = t; this.lastLoaded = this.loaded; }    this.last ??= t; this.lastLoaded ??= this.loaded;    this.onProgress({ state: this.state, loaded: this.loaded, total: this.file.size, speed: this.speed,      eta: this.speed > 0 ? (this.file.size - this.loaded) / this.speed : Infinity });  }  setState(s) { this.state = s; this.emit(); }  pause() { if (this.state === "uploading") { this.setState("paused"); this.ctl?.abort(); } }  async cancel() {    const was = this.state; this.setState("canceled"); this.ctl?.abort();    if (this.id && was !== "done") await this.f(`/api/uploads/${this.id}`, { method: "DELETE" }).catch(() => {});  }  async json(path, init) {    const r = await this.f(path, init);    if (!r.ok) { const e = new Error(`HTTP ${r.status}`); e.fatal = r.status >= 400 && r.status < 500 && r.status !== 429 && r.status !== 408; throw e; }    return r.json();  }  // start or resume; resolves {id,name,size,type} when done, or null if paused/canceled  async run() {    if (this.state === "canceled") return null;    this.setState("uploading"); this.ctl = new AbortController();    const sig = this.ctl.signal;    try {      const file = this.file, type = file.type || "application/octet-stream";      if (!this.id) {        const c = await withRetry(() => this.json("/api/uploads", { method: "POST", headers: { "content-type": "application/json" },          body: JSON.stringify({ name: file.name, size: file.size, type, multipart: this.multipart }) }), { wait: this.wait, signal: sig });        this.id = c.id; this.info = c;      }      if (this.multipart && this.info.multipart !== false) await this.runParts(sig);      else {        await withRetry(() => this.json(`/api/uploads/${this.id}?name=${encodeURIComponent(file.name)}`, { method: "PUT", body: file,          headers: { "content-type": type }, signal: sig }), { wait: this.wait, signal: sig });        this.loaded = file.size;      }      this.setState("done");      return { id: this.id, name: file.name, size: file.size, type };    } catch (e) {      if (this.state === "paused" || this.state === "canceled") return null;      this.error = e; this.setState("error"); throw e;    }  }  async runParts(sig) {    const ps = this.info.partSize || PART_SIZE, plan = planParts(this.file.size, ps).filter((p) => !this.done.has(p.n));    const queue = [...plan];    const recalc = () => { this.loaded = [...this.done.values()].reduce((s, d) => s + d.size, 0); this.emit(); };    recalc();    const worker = async () => {      for (let p; (p = queue.shift()) && !sig.aborted;) {        const body = this.file.slice(p.start, p.end);        const r = await withRetry(() => this.json(`/api/uploads/${this.id}/parts/${p.n}`, { method: "PUT", body, signal: sig }),          { wait: this.wait, signal: sig });        this.done.set(p.n, { etag: r.etag, size: p.end - p.start }); recalc();      }    };    await Promise.all(Array.from({ length: Math.min(CONCURRENCY, plan.length) }, worker));    if (sig.aborted) throw Object.assign(new Error("aborted"), { name: "AbortError" });    const parts = [...this.done].sort((a, b) => a[0] - b[0]).map(([partNumber, d]) => ({ partNumber, etag: d.etag }));    await withRetry(() => this.json(`/api/uploads/${this.id}/complete`, { method: "POST", headers: { "content-type": "application/json" },      body: JSON.stringify({ parts }) }), { wait: this.wait, signal: sig });  }}