File size: 9,814 Bytes
12ce07b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import Dexie, { type Table } from "dexie";
import { name } from "../../package.json";
import { addLogEntry } from "./logEntries";
import { getSearchTokenHash } from "./searchTokenHash";
import type { ImageSearchResults, TextSearchResults } from "./types";

const cacheConfig = {
  ttl: 15 * 60 * 1000,
  maxEntries: 100,
  enabled: true,
};

const cacheMetrics = {
  textHits: 0,
  textMisses: 0,
  imageHits: 0,
  imageMisses: 0,

  getTextHitRate(): number {
    const total = this.textHits + this.textMisses;
    return total > 0 ? this.textHits / total : 0;
  },

  getImageHitRate(): number {
    const total = this.imageHits + this.imageMisses;
    return total > 0 ? this.imageHits / total : 0;
  },

  logPerformance(): void {
    addLogEntry(
      `Cache performance - Text: ${(this.getTextHitRate() * 100).toFixed(1)}% hits, ` +
        `Image: ${(this.getImageHitRate() * 100).toFixed(1)}% hits`,
    );
  },
};

interface SearchCacheEntry {
  key: string;
  timestamp: number;
}

interface TextSearchCache extends SearchCacheEntry {
  results: TextSearchResults;
}

interface ImageSearchCache extends SearchCacheEntry {
  results: ImageSearchResults;
}

class SearchDb extends Dexie {
  textSearchHistory!: Table<TextSearchCache, string>;
  imageSearchHistory!: Table<ImageSearchCache, string>;

  constructor() {
    super(name);
    this.version(1).stores({
      textSearchHistory: "key, timestamp",
      imageSearchHistory: "key, timestamp",
    });
  }

  async ensureIntegrity(): Promise<void> {
    try {
      await this.textSearchHistory.count();
    } catch (error) {
      addLogEntry(
        `Database integrity check failed, rebuilding: ${error instanceof Error ? error.message : String(error)}`,
      );
      try {
        await this.delete();
        await this.open();
      } catch (recoveryError) {
        addLogEntry(
          `Failed to recover database: ${recoveryError instanceof Error ? recoveryError.message : String(recoveryError)}`,
        );
        cacheConfig.enabled = false;
      }
    }
  }

  async cleanExpiredCache(
    storeName: "textSearchHistory" | "imageSearchHistory",
    timeToLive: number = cacheConfig.ttl,
  ): Promise<void> {
    const currentTime = Date.now();
    const store = this[storeName];

    try {
      const expiredItems = await store
        .where("timestamp")
        .below(currentTime - timeToLive)
        .toArray();

      if (expiredItems.length > 0) {
        await store.bulkDelete(expiredItems.map((item) => item.key));
        addLogEntry(
          `Removed ${expiredItems.length} expired items from ${storeName}`,
        );
      }
    } catch (error) {
      addLogEntry(
        `Error cleaning expired cache: ${error instanceof Error ? error.message : String(error)}`,
      );
    }
  }

  async pruneCache(
    storeName: "textSearchHistory" | "imageSearchHistory",
    maxEntries: number = cacheConfig.maxEntries,
  ): Promise<void> {
    try {
      const store = this[storeName];
      const count = await store.count();

      if (count > maxEntries) {
        const excess = count - maxEntries;
        const oldestEntries = await store
          .orderBy("timestamp")
          .limit(excess)
          .primaryKeys();

        if (oldestEntries.length > 0) {
          await store.bulkDelete(oldestEntries);
          addLogEntry(
            `Pruned ${oldestEntries.length} oldest entries from ${storeName}`,
          );
        }
      }
    } catch (error) {
      addLogEntry(
        `Error pruning cache: ${error instanceof Error ? error.message : String(error)}`,
      );
    }
  }

  async getCachedResult<T extends TextSearchResults | ImageSearchResults>(
    storeName: "textSearchHistory" | "imageSearchHistory",
    key: string,
  ): Promise<{ results: T; fresh: boolean } | null> {
    if (!cacheConfig.enabled) return null;

    try {
      const store = this[storeName] as Table<
        { key: string; results: T; timestamp: number },
        string
      >;
      const cachedItem = await store.get(key);

      if (!cachedItem) return null;

      const fresh = Date.now() - cachedItem.timestamp < cacheConfig.ttl;
      return { results: cachedItem.results, fresh };
    } catch (error) {
      addLogEntry(
        `Error retrieving from cache: ${error instanceof Error ? error.message : String(error)}`,
      );
      return null;
    }
  }

  async cacheResult<T extends TextSearchResults | ImageSearchResults>(
    storeName: "textSearchHistory" | "imageSearchHistory",
    key: string,
    results: T,
  ): Promise<void> {
    if (!cacheConfig.enabled) return;

    try {
      const store = this[storeName] as Table<
        { key: string; results: T; timestamp: number },
        string
      >;
      await store.put({
        key,
        results,
        timestamp: Date.now(),
      });

      this.pruneCache(storeName).catch((error) => {
        addLogEntry(
          `Error during cache pruning: ${error instanceof Error ? error.message : String(error)}`,
        );
      });
    } catch (error) {
      addLogEntry(
        `Error caching results: ${error instanceof Error ? error.message : String(error)}`,
      );
    }
  }
}

const db = new SearchDb();

db.ensureIntegrity().catch((error) => {
  addLogEntry(
    `Database initialization error: ${error instanceof Error ? error.message : String(error)}`,
  );
});

const searchService = {
  hashQuery(query: string): string {
    return query
      .split("")
      .reduce((acc, char) => ((acc << 5) - acc + char.charCodeAt(0)) | 0, 0)
      .toString(36);
  },

  async performSearch<T>(
    endpoint: "text" | "images",
    query: string,
    limit?: number,
  ): Promise<T> {
    const searchUrl = new URL(`/search/${endpoint}`, self.location.origin);
    searchUrl.searchParams.set("q", query);
    searchUrl.searchParams.set("token", await getSearchTokenHash());
    if (limit) searchUrl.searchParams.set("limit", limit.toString());

    const response = await fetch(searchUrl.toString());
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  },

  async searchText(query: string, limit?: number): Promise<TextSearchResults> {
    try {
      await db.cleanExpiredCache("textSearchHistory");

      const key = this.hashQuery(query);
      const cachedData = await db.getCachedResult<TextSearchResults>(
        "textSearchHistory",
        key,
      );

      if (cachedData?.fresh) {
        cacheMetrics.textHits++;
        addLogEntry(
          `Text search cache hit for "${query}" (${cachedData.results.length} results)`,
        );
        return cachedData.results;
      }

      cacheMetrics.textMisses++;
      addLogEntry(`Text search cache miss for "${query}", fetching from API`);

      const results = await this.performSearch<TextSearchResults>(
        "text",
        query,
        limit,
      );

      await db.cacheResult("textSearchHistory", key, results);

      if ((cacheMetrics.textHits + cacheMetrics.textMisses) % 10 === 0) {
        cacheMetrics.logPerformance();
      }

      return results;
    } catch (error) {
      addLogEntry(
        `Text search failed: ${error instanceof Error ? error.message : String(error)}`,
      );
      return [];
    }
  },

  async searchImages(
    query: string,
    limit?: number,
  ): Promise<ImageSearchResults> {
    try {
      await db.cleanExpiredCache("imageSearchHistory");

      const key = this.hashQuery(query);
      const cachedData = await db.getCachedResult<ImageSearchResults>(
        "imageSearchHistory",
        key,
      );

      if (cachedData?.fresh) {
        cacheMetrics.imageHits++;
        addLogEntry(
          `Image search cache hit for "${query}" (${cachedData.results.length} results)`,
        );
        return cachedData.results;
      }

      cacheMetrics.imageMisses++;
      addLogEntry(`Image search cache miss for "${query}", fetching from API`);

      const results = await this.performSearch<ImageSearchResults>(
        "images",
        query,
        limit,
      );

      await db.cacheResult("imageSearchHistory", key, results);

      if ((cacheMetrics.imageHits + cacheMetrics.imageMisses) % 10 === 0) {
        cacheMetrics.logPerformance();
      }

      return results;
    } catch (error) {
      addLogEntry(
        `Image search failed: ${error instanceof Error ? error.message : String(error)}`,
      );
      return [];
    }
  },

  async clearSearchCache(): Promise<void> {
    try {
      await db.delete();
      db.version(1).stores({
        textSearchHistory: "key, timestamp",
        imageSearchHistory: "key, timestamp",
      });
      await db.open();

      cacheMetrics.textHits = 0;
      cacheMetrics.textMisses = 0;
      cacheMetrics.imageHits = 0;
      cacheMetrics.imageMisses = 0;

      addLogEntry("Search cache cleared successfully");
    } catch (error) {
      addLogEntry(
        `Failed to clear search cache: ${error instanceof Error ? error.message : String(error)}`,
      );
    }
  },

  getCacheStats() {
    return {
      textHitRate: cacheMetrics.getTextHitRate(),
      imageHitRate: cacheMetrics.getImageHitRate(),
      textHits: cacheMetrics.textHits,
      textMisses: cacheMetrics.textMisses,
      imageHits: cacheMetrics.imageHits,
      imageMisses: cacheMetrics.imageMisses,
      config: { ...cacheConfig },
    };
  },

  updateCacheConfig(newConfig: Partial<typeof cacheConfig>) {
    Object.assign(cacheConfig, newConfig);
    addLogEntry(
      `Cache configuration updated: TTL=${cacheConfig.ttl}ms, maxEntries=${cacheConfig.maxEntries}, enabled=${cacheConfig.enabled}`,
    );
  },
};

export const searchText = searchService.searchText.bind(searchService);
export const searchImages = searchService.searchImages.bind(searchService);