cacheModel method

Future<void> cacheModel(
  1. String url,
  2. Uint8List data
)

Cache a model

Stores binary data in Cache API and metadata in SharedPreferences. Uses URL normalization.

Throws if storage quota exceeded or other error.

Implementation

Future<void> cacheModel(String url, Uint8List data) async {
  try {
    final normalizedUrl = UrlUtils.normalizeUrl(url);

    if (kDebugMode) {
      gemmaLog(
        'WebCacheService: cacheModel($url) size: ${data.length} bytes, normalized: $normalizedUrl',
      );
    }

    // Store in Cache API
    await _cacheInterop.put(cacheName, normalizedUrl, data);

    // Store metadata
    await _saveMetadata(
      CacheMetadata(
        url: url,
        sizeInBytes: data.length,
        timestamp: DateTime.now(),
        cacheKey: normalizedUrl,
      ),
    );

    if (kDebugMode) {
      gemmaLog('[WebCacheService] ✅ Successfully cached $url');
    }
  } catch (e) {
    gemmaLog('[WebCacheService] ❌ cacheModel failed for $url: $e');

    // Handle QuotaExceededError
    if (e.toString().contains('quota')) {
      gemmaLog(
        '[WebCacheService] ⚠️  Storage quota exceeded, attempting cleanup',
      );
      await _cleanupOldEntries();
      // Retry once after cleanup
      try {
        final normalizedUrl = UrlUtils.normalizeUrl(url);
        await _cacheInterop.put(cacheName, normalizedUrl, data);
        await _saveMetadata(
          CacheMetadata(
            url: url,
            sizeInBytes: data.length,
            timestamp: DateTime.now(),
            cacheKey: normalizedUrl,
          ),
        );
        gemmaLog('[WebCacheService] ✅ Cached after cleanup: $url');
        return;
      } catch (retryError) {
        gemmaLog('[WebCacheService] ❌ Retry failed: $retryError');
      }
    }

    rethrow;
  }
}