summaryrefslogtreecommitdiffhomepage
path: root/src/lib/components/CacheDebug.svelte
blob: 09e859d8f26c36898173409f2bf0cb9ccb955409 (plain)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
<script lang="ts">
  import { imageCache } from '../cache';

  interface CacheStats {
    entries: number;
    fullCount: number;
    thumbCount: number;
    totalBytes: number;
    idbEntries: number;
    idbBytes: number;
    idbError: string | undefined;
    idbLastWriteError: string | undefined;
    idbWriteErrorCount: number;
  }

  let stats = $state<CacheStats | undefined>(undefined);
  let refreshing = $state(false);
  let collapsed = $state(false);

  function formatBytes(bytes: number): string {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    const val = bytes / Math.pow(k, i);
    return `${val.toFixed(1)} ${sizes[i]}`;
  }

  let storageEstimate = $state<{ usage: number; quota: number } | undefined>(undefined);
  let storageError = $state<string | undefined>(undefined);

  async function refresh() {
    refreshing = true;
    try {
      stats = await imageCache.getStats();
    } catch { /* ignore */ }

    // Try standard Storage API first, then webkit fallback
    storageEstimate = undefined;
    storageError = undefined;
    try {
      if (navigator.storage && navigator.storage.estimate) {
        const est = await navigator.storage.estimate();
        storageEstimate = { usage: est.usage ?? 0, quota: est.quota ?? 0 };
      } else if ('webkitTemporaryStorage' in navigator) {
        // Chrome HTTP fallback
        const wk = (navigator as Record<string, unknown>)['webkitTemporaryStorage'] as
          { queryUsageAndQuota: (ok: (u: number, q: number) => void, err: (e: unknown) => void) => void } | undefined;
        if (wk !== undefined) {
          const result = await new Promise<{ usage: number; quota: number }>((resolve, reject) => {
            wk.queryUsageAndQuota(
              (usage, quota) => resolve({ usage, quota }),
              (err) => reject(err),
            );
          });
          storageEstimate = result;
        } else {
          storageError = 'Storage API not available (HTTP origin)';
        }
      } else {
        storageError = 'Storage API not available';
      }
    } catch (e) {
      storageError = e instanceof Error ? e.message : String(e);
    }

    refreshing = false;
  }

  $effect(() => {
    void refresh();
    const id = setInterval(() => { void refresh(); }, 2000);
    return () => clearInterval(id);
  });
</script>

<div class="fixed top-2 left-2 z-50 bg-base-100/95 backdrop-blur-sm rounded-box shadow-lg border border-base-300 p-3 text-xs font-mono max-w-80 pointer-events-auto">
  <button
    class="flex items-center justify-between w-full mb-1"
    onclick={() => collapsed = !collapsed}
  >
    <span class="font-bold text-sm">Cache Debug</span>
    <span class="text-base-content/50">{collapsed ? '▶' : '▼'}</span>
  </button>

  {#if !collapsed && stats !== undefined}
    <div class="space-y-2">
      <!-- Memory Cache -->
      <div>
        <div class="font-semibold text-primary">Memory Cache</div>
        <div>Entries: <span class="text-info">{stats.entries}</span> ({stats.fullCount} full, {stats.thumbCount} thumb)</div>
        <div>Size: <span class="text-info">{formatBytes(stats.totalBytes)}</span></div>
      </div>

      <!-- IndexedDB -->
      <div class="border-t border-base-300 pt-2">
        <div class="font-semibold text-secondary">IndexedDB</div>
        {#if stats.idbError !== undefined}
          <div class="text-error">Error: {stats.idbError}</div>
        {:else}
          <div>Entries: <span class="text-info">{stats.idbEntries}</span></div>
          <div>Size: <span class="text-info">{formatBytes(stats.idbBytes)}</span></div>
          {#if stats.idbWriteErrorCount > 0}
            <div class="text-error mt-1">❌ {stats.idbWriteErrorCount} write errors</div>
            {#if stats.idbLastWriteError !== undefined}
              <div class="text-error text-[10px] break-all">{stats.idbLastWriteError}</div>
            {/if}
          {/if}
          <div class="mt-1">
            {#if stats.idbEntries === stats.entries}
              <span class="text-success">✅ In sync with memory</span>
            {:else if stats.idbEntries < stats.entries}
              <span class="text-warning">⏳ IDB behind ({stats.entries - stats.idbEntries} pending)</span>
            {:else}
              <span class="text-info">IDB has {stats.idbEntries - stats.entries} extra (pre-loaded)</span>
            {/if}
          </div>
        {/if}
      </div>
      <!-- Storage Quota -->
      <div class="border-t border-base-300 pt-2">
        <div class="font-semibold text-accent">Storage Quota</div>
        {#if storageEstimate !== undefined}
          <div>Used: <span class="text-info">{formatBytes(storageEstimate.usage)}</span> / {formatBytes(storageEstimate.quota)}</div>
          {#if storageEstimate.quota > 0}
            {@const pct = (storageEstimate.usage / storageEstimate.quota * 100)}
            <div>
              <progress class="progress progress-primary w-full h-2" value={pct} max="100"></progress>
              <span class:text-error={pct > 90} class:text-warning={pct > 70 && pct <= 90}>{pct.toFixed(1)}%</span>
            </div>
          {/if}
        {:else if storageError !== undefined}
          <div class="text-warning">{storageError}</div>
        {:else}
          <div class="text-base-content/50">Querying…</div>
        {/if}
      </div>
    </div>
  {:else if !collapsed}
    <div class="text-base-content/50">
      {#if refreshing}Loading…{:else}No data{/if}
    </div>
  {/if}
</div>