UrlFileCache class

UrlFileCache

A lightweight, decoupled, RFC 7234-compliant URL-to-local-file cache manager featuring HTTP 304 validation, in-flight request deduplication, atomic file writes, and graceful offline fallback.


Design Intent

Fetching remote assets (e.g. images, documents, Markdown, config files) is a common requirement in client applications. Standard HTTP caching often involves bloated third-party dependencies, complex local database schemas, or rigid caching rules that fail when offline.

UrlFileCache was designed to be:

  1. Zero Project-Specific Dependencies: Operates strictly on dart:io, standard HTTP primitives, and minimal file hashing utilities.

  2. Compliant with HTTP RFC 7234: Persists response headers in companion metadata (.meta.json) files to negotiate cache validity using If-None-Match (ETag) and If-Modified-Since (Last-Modified), leveraging 304 Not Modified.

  3. Single-Flight Request Deduplication: Transparently shares active Future instances when identical concurrent URL requests occur simultaneously (e.g., multiple UI widgets loading the same avatar or document), preventing redundant bandwidth consumption and race conditions.

  4. Resilient & Atomic: Employs atomic write-then-rename routines (.tmp -> target) to guarantee partial or interrupted writes never poison the cache.

  5. Graceful Offline Fallback: Returns existing local cache copies when the network drops or upstream servers encounter unexpected errors.

  6. Zero-Latency Synchronous Lookup: Exposes getCachedFile for instant, network-free disk cache checks without async scheduling overhead:

    getCachedFile(url) ─▶ trim ─▶ FNV-1a 64-bit hash ─▶ existsSync() ─▶ File?
    (sync, disk-only)                                                    │
                                      ┌── null / stale? ◀────────────────┘
                                      ▼
                               getFile(url) ─▶ TTL check ─▶ HTTP 304 / 200
    

Typical Use Cases

  • Remote Document & Asset Caching: Markdown files, EULAs, Terms of Service, remote help manuals, and release notes.
  • Media & Image Buffering: Avatars, cover artwork, and static remote media files.
  • Configuration & Remote Presets: Caching remote schema files, model definitions, or remote JSON configurations.
  • Synchronous Cache-First UI & Offline Checks: Using getCachedFile to immediately render already-cached assets on the first UI frame (avoiding async flicker) or to inspect local cache availability in strict offline flows without triggering any network request.

Usage Examples

1. Minimal Example (Beginners)

import 'dart:io';
import 'package:basic_http_interceptor/utils/url_file_cache.dart';

void main() async {
  final cacheDir = Directory('/path/to/cache');
  final fileCache = UrlFileCache(cacheDir);

  // Fetch remote file (caches automatically or returns local copy on 304)
  final file = await fileCache.getFile('https://example.com/readme.md');
  if (file != null) {
    print('Cached file ready at: ${file.path}');
    print(await file.readAsString());
  }

  // Clean up when shutting down
  fileCache.close();
}

2. Advanced Example (Power Users)

Custom HTTP client, local TTL freshness validation, forced re-validation, and plain-text helper:

import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:basic_http_interceptor/utils/url_file_cache.dart';

void main() async {
  final customClient = http.Client();
  final cache = UrlFileCache(
    Directory('/path/to/cache'),
    client: customClient,
  );

  const url = 'https://example.com/config.json';

  // 1. Skip network calls entirely if cached within the last 15 minutes
  final freshFile = await cache.getFile(
    url,
    ttl: const Duration(minutes: 15),
  );

  // 2. Force network revalidation regardless of local TTL
  final updatedFile = await cache.getFile(
    url,
    forceRefresh: true,
  );

  // 3. Convenience helper: fetch remote text directly
  final text = await cache.getText(
    Uri.parse('https://example.com/changelog.txt'),
    ttl: const Duration(hours: 1),
  );
  print('Changelog:\n$text');

  cache.close();
}

3. Synchronous Cache-Only Lookup

Check whether a URL is already cached on disk without triggering network I/O (e.g., for instant first-frame UI rendering before background revalidation):

import 'dart:io';
import 'package:basic_http_interceptor/utils/url_file_cache.dart';

void renderAvatar(UrlFileCache cache, String avatarUrl) async {
  // 1. Synchronous disk-only check (never hits the network)
  final cached = cache.getCachedFile(avatarUrl);
  if (cached != null) {
    print('Render immediately from disk: ${cached.path}');
  }

  // 2. Optionally revalidate in the background with HTTP 304 / TTL
  final latest = await cache.getFile(
    avatarUrl,
    ttl: const Duration(minutes: 10),
  );
  if (latest != null && latest.path != cached?.path) {
    print('Updated cache ready at: ${latest.path}');
  }
}

Constructors

UrlFileCache(Directory cacheDir, {Client? client})
Creates a UrlFileCache storing files within cacheDir.

Properties

cacheDir → Directory
The root directory where cached files are stored.
final
hashCode → int
The hash code for this object.
no setterinherited
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited

Methods

close() → void
Closes the underlying HTTP client if it was created internally and clears any pending in-flight request tracking.
getCachedFile(String url) → File?
Synchronously checks if a local cached file exists for url. Returns the File if it exists, or null otherwise.
getFile(String url, {Duration? ttl, bool forceRefresh = false}) → Future<File?>
Fetches the file corresponding to url from the local cache or over the network.
getText(Uri uri, {Duration? ttl, bool forceRefresh = false}) → Future<String>
Fetches plain text (UTF-8 string) from a Uri.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() → String
A string representation of this object.
inherited

Operators

operator ==(Object other) → bool
The equality operator.
inherited