सामग्री पर जाएँ
HexaTransfer
ब्लॉग पर वापस
तकनीकी गहन विश्लेषण

ऑफ़लाइन ट्रांसफर के लिए सर्विस वर्कर फ़ाइल कैशिंग

ऑफ़लाइन फ़ाइल ट्रांसफर क्षमताओं को सक्षम करने के लिए Service Workers का उपयोग करें। कैश रणनीतियाँ, बैकग्राउंड सिंक और प्रोग्रेसिव वेब ऐप पैटर्न।

Service Workers network drop होने पर file transfer app को काम करते रहने देते हैं: Cache API के साथ HTML shell और JS cache करें, Background Sync API के साथ failed uploads queue करें, IndexedDB में partial chunks store करें, और connectivity return होने पर सब कुछ replay करें। Worker अपने event loop के साथ separate thread पर चलता है, अपने scope के लिए fetch events intercept करता है, और tab closes के बाद persist करता है। Upload tools के लिए, सही recipe है: app shell के लिए stale-while-revalidate strategy, in-flight transfers के लिए IndexedDB-backed chunk queuing, और periodic Background Sync registration जो uploads 15 मिनट हर बार retry करता है जब तक success न हो।

Service Workers Transfer Apps के लिए वास्तव में क्या करते हैं

बड़ा फायदा यह है कि navigator.serviceWorker tab reloads, offline periods, और यहाँ तक कि phone sleep survive करता है। जब user flaky train Wi-Fi पर 2 GB upload शुरू करता है, तो आप चाहते हैं कि पहले से succeed हुए chunks succeed रहें, in-flight chunks reconnection पर retry करें, और tab kill होने पर पूरा state recoverable हो। Service Worker — जो किसी specific tab से independent चलता है — वह piece है जो यह सब enable करता है।

API तीन building blocks देता है: URLs द्वारा responses store करने के लिए Cache, structured data (chunk queues, session state) के लिए IndexedDB, और retries schedule करने के लिए SyncManager जो device online होने पर fire होते हैं।

Worker Register और Version करना

App load पर एक बार register करें और updates explicitly handle करें:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js', { scope: '/' })
    .then((reg) => reg.addEventListener('updatefound', () => {
      const sw = reg.installing;
      sw.addEventListener('statechange', () => {
        if (sw.state === 'installed' && navigator.serviceWorker.controller) {
          // new version ready, user को refresh prompt करें
        }
      });
    }));
}

Cache keys version करें (transfer-v7) ताकि new deploy stale JavaScript behind छोड़े बिना old assets invalidate करे। Classic bug: index.html हमेशा के लिए cache होती है, users update कभी नहीं पाते, और आप weeks तक Slack पर debug कर रहे हैं। Caches को build hashes पर pin करें और activate event में clean up करें।

App Shell बनाम User Data के लिए Caching Strategies

अलग-अलग resources अलग-अलग strategies deserve करते हैं:

  • App shell (HTML, CSS, JS, icons): network fallback के साथ cache-first। Instant loads, offline काम करता है।
  • API metadata (/shares/:id): cache fallback के साथ network-first, 60-second TTL। Online होने पर fresh, नहीं होने पर usable।
  • File bytes: कभी cache नहीं। Files अक्सर multi-gigabyte होती हैं और Cache API में origin quotas होते हैं (typically 60% of free disk)।
  • CDNs से Fonts: stale-while-revalidate। Fast और auto-refreshing।

fetch handler में:

self.addEventListener('fetch', (e) => {
  const url = new URL(e.request.url);
  if (url.pathname.startsWith('/assets/')) {
    e.respondWith(cacheFirst(e.request, 'shell-v7'));
  } else if (url.pathname.startsWith('/api/shares/')) {
    e.respondWith(networkFirst(e.request, 'api-v1', 60));
  }
});

Binary file uploads के लिए requests कभी intercept न करें — e.request.method === 'PUT' check करके और early return करके उनके around route करें। Worker के माध्यम से gigabyte PUTs proxy करना memory disaster है।

Background Sync के साथ Failed Uploads Queue करना

SyncManager resilient uploads की key है। जब chunk PUT fail हो, इसे IndexedDB में stash करें और sync register करें:

// page code में
const reg = await navigator.serviceWorker.ready;
await reg.sync.register('flush-uploads');
// sw.js में
self.addEventListener('sync', (event) => {
  if (event.tag === 'flush-uploads') {
    event.waitUntil(flushPendingUploads());
  }
});

Browser sync event network वापस आने पर fire करता है, ~24 घंटों तक exponential backoff के साथ। Chrome और Edge support करते हैं; Safari ने 17.5 में "Background Fetch" flag के तहत subset ship किया लेकिन user permission require करता है। Safari के लिए, visibilitychange के माध्यम से next visible page open पर retry करने पर fall back करें।

Background Fetch API large file operations के लिए specially designed अलग tool है — यह browser UI में persistent notification दिखाता है ताकि users tab close करने के बाद भी progress track कर सकें। 500 MB से अधिक uploads के लिए worth using है।

IndexedDB में Partial Uploads Store करना

IndexedDB आपका durable scratch space है। एक बार small database open करें, फिर session metadata plus chunk offsets stash करें:

const db = await openDB('transfers', 1, {
  upgrade(db) {
    db.createObjectStore('sessions', { keyPath: 'id' });
    db.createObjectStore('chunks', { keyPath: ['sessionId', 'index'] });
  }
});
await db.put('sessions', {
  id, fileName, fileSize, fileFingerprint, createdAt: Date.now(),
  completedIndexes: [], partUrls
});

Raw chunk bytes store न करें — वे File handle से आते हैं, जिसे IndexedDB structured clone reference के रूप में persist कर सकता है जो reloads के बाद valid रहता है। Handle store करने से database में 2 GB bytes duplicate करना avoid होता है।

Origin storage की limits हैं: desktop Chrome पर roughly 60% of free disk, iOS Safari पर eviction pressure kick होने से पहले प्रति origin 1 GB। "Persistent" bucket पाने के लिए navigator.storage.persist() request करें जिसे browsers automatically evict करने से avoid करते हैं।

Offline और Online Transitions Handle करना

Page और service worker दोनों में online और offline events listen करें:

// page
window.addEventListener('online', () => {
  ui.showBanner('वापस online — uploads resume हो रहे हैं');
  navigator.serviceWorker.controller?.postMessage({ type: 'resume' });
});
window.addEventListener('offline', () => {
  ui.showBanner('Offline — uploads रुके हुए हैं');
});

navigator.onLine corporate captive portals पर notoriously unreliable है — यह true report करता है जब device का local network connection है लेकिन internet नहीं। Trustworthy detection के लिए, 3-second timeout के साथ tiny fetch('/ping', { cache: 'no-store' }) करें।

इसे Proper PWA बनाना

display: standalone, icon set, और start_url: / के साथ manifest.json ship करें। iOS के लिए apple-touch-icon links add करें। File handling declare करें ताकि OS आपकी app को specific extensions के साथ associate कर सके:

{
  "name": "Hex Transfer",
  "file_handlers": [{
    "action": "/share-target",
    "accept": { "application/*": [".pdf", ".zip", ".docx"] }
  }]
}

Web Share Target के साथ combined, यह users को OS share sheet से सीधे आपकी app में files share करने देता है। Chrome Android और desktop Chromium पर, PWA उन file types के लिए default handler के रूप में register हो सकता है जो आप declare करते हैं। यह browser page को native upload tool की तरह behave करने वाली app में बदलता है।

Offline Story Test करना

तीन scenarios manually test करने के लिए, क्योंकि automated offline tests flaky हैं:

  1. Fast Wi-Fi पर 500 MB upload शुरू करें, 30% पर airplane mode switch करें, 30 seconds wait करें, Wi-Fi वापस चालू करें। Upload बिना user action के जहाँ रुका था वहाँ से resume होना चाहिए।
  2. Upload शुरू करें, 60% पर tab close करें, 2 मिनट wait करें, reopen करें। Session resume करने का offer करें।
  3. Mobile पर upload शुरू करें, 5 मिनट के लिए screen lock करें। Background sync unlock होने पर fire होना चाहिए और transfer finish करना चाहिए।

Chrome DevTools का "Offline" checkbox और Application > Service Workers > Update on reload indispensable हैं। Network panel के "Throttling" profiles Fast 3G और Slow 3G simulate करने देते हैं यह देखने के लिए कि आपका error UI कैसे behave करता है।

HexaTransfer का web app app-shell caching के लिए Service Worker और in-flight session state के लिए IndexedDB उपयोग करता है, इसलिए reloads और brief offline periods upload progress नहीं खोते। hexatransfer.com पर मुफ्त में आज़माएं — कोई खाता नहीं, 10 GB अधिकतम।

जानने लायक Pitfalls

Service Workers के कुछ gotchas हैं जो newcomers को bite करते हैं: वे केवल HTTPS पर काम करते हैं (localhost को छोड़कर), cache quotas browsers में wildly vary करते हैं, iOS Safari Background Sync के लिए workers को reliably wake नहीं करता, DevTools stale workers aggressively cache कर सकता है (develop करते समय हमेशा "Bypass for network" click करें), और importScripts install के दौरान synchronously run होता है इसलिए वहाँ slow third-party scripts कभी fetch न करें। एक small integration test लिखें जो check करे कि worker activate होता है, clients claim करता है, और offline page serve करता है — वह single test 80% regressions catch करता है जो आप production में hit करेंगे।

एंड-टू-एंड एन्क्रिप्शन के साथ बड़ी फ़ाइलें सुरक्षित रूप से भेजें

एंड-टू-एंड एन्क्रिप्शन के साथ 10 GB तक की फ़ाइलें मुफ़्त में ट्रांसफ़र करें। अकाउंट की आवश्यकता नहीं। अपलोड से पहले आपकी फ़ाइलें ब्राउज़र में एन्क्रिप्ट की जाती हैं — कोई और उन्हें पढ़ नहीं सकता।

फ़ाइल भेजें