sehawq.db 3.0.0 โ†’ 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,339 @@
1
+ /**
2
+ * Smart Cache System - Makes everything faster with magic ๐Ÿช„
3
+ *
4
+ * Implements LRU cache with TTL and memory management
5
+ * Because waiting is not an option in 2024 โšก
6
+ */
7
+
8
+ class Cache {
9
+ constructor(options = {}) {
10
+ this.options = {
11
+ maxSize: 1000,
12
+ ttl: 5 * 60 * 1000, // 5 minutes default
13
+ cleanupInterval: 60 * 1000, // Clean every minute
14
+ ...options
15
+ };
16
+
17
+ // Double-linked list for LRU + HashMap for O(1) access
18
+ this.cache = new Map();
19
+ this.head = { key: null, value: null, next: null, prev: null, expires: 0 };
20
+ this.tail = { key: null, value: null, next: null, prev: this.head, expires: 0 };
21
+ this.head.next = this.tail;
22
+
23
+ this.stats = {
24
+ hits: 0,
25
+ misses: 0,
26
+ evictions: 0,
27
+ sets: 0,
28
+ gets: 0,
29
+ memoryUsage: 0
30
+ };
31
+
32
+ this._startCleanupInterval();
33
+ }
34
+
35
+ /**
36
+ * Get value from cache - moves item to front (most recently used)
37
+ */
38
+ get(key) {
39
+ this.stats.gets++;
40
+
41
+ const node = this.cache.get(key);
42
+
43
+ // Check if exists and not expired
44
+ if (!node || this._isExpired(node)) {
45
+ this.stats.misses++;
46
+
47
+ if (node) {
48
+ // Remove expired node
49
+ this._removeNode(node);
50
+ this.cache.delete(key);
51
+ this.stats.evictions++;
52
+ }
53
+
54
+ return undefined;
55
+ }
56
+
57
+ // Move to front (most recently used)
58
+ this._moveToFront(node);
59
+ this.stats.hits++;
60
+
61
+ return node.value;
62
+ }
63
+
64
+ /**
65
+ * Set value in cache - handles LRU eviction if needed
66
+ */
67
+ set(key, value, ttl = this.options.ttl) {
68
+ this.stats.sets++;
69
+
70
+ let node = this.cache.get(key);
71
+ const expires = Date.now() + ttl;
72
+
73
+ if (node) {
74
+ // Update existing node
75
+ node.value = value;
76
+ node.expires = expires;
77
+ this._moveToFront(node);
78
+ } else {
79
+ // Create new node
80
+ node = {
81
+ key,
82
+ value,
83
+ expires,
84
+ prev: this.head,
85
+ next: this.head.next
86
+ };
87
+
88
+ // Add to cache and linked list
89
+ this.cache.set(key, node);
90
+ this.head.next.prev = node;
91
+ this.head.next = node;
92
+
93
+ // Evict if over capacity
94
+ if (this.cache.size > this.options.maxSize) {
95
+ this._evictLRU();
96
+ }
97
+ }
98
+
99
+ // Update memory usage stats
100
+ this._updateMemoryStats();
101
+
102
+ return true;
103
+ }
104
+
105
+ /**
106
+ * Check if key exists in cache (without updating LRU)
107
+ */
108
+ has(key) {
109
+ const node = this.cache.get(key);
110
+ return !!(node && !this._isExpired(node));
111
+ }
112
+
113
+ /**
114
+ * Delete key from cache
115
+ */
116
+ delete(key) {
117
+ const node = this.cache.get(key);
118
+ if (node) {
119
+ this._removeNode(node);
120
+ this.cache.delete(key);
121
+ return true;
122
+ }
123
+ return false;
124
+ }
125
+
126
+ /**
127
+ * Clear entire cache
128
+ */
129
+ clear() {
130
+ this.cache.clear();
131
+ this.head.next = this.tail;
132
+ this.tail.prev = this.head;
133
+ this.stats.memoryUsage = 0;
134
+ }
135
+
136
+ /**
137
+ * Get cache size (number of items)
138
+ */
139
+ size() {
140
+ return this.cache.size;
141
+ }
142
+
143
+ /**
144
+ * Get all keys in cache (for debugging)
145
+ */
146
+ keys() {
147
+ const keys = [];
148
+ let node = this.head.next;
149
+
150
+ while (node !== this.tail) {
151
+ if (!this._isExpired(node)) {
152
+ keys.push(node.key);
153
+ }
154
+ node = node.next;
155
+ }
156
+
157
+ return keys;
158
+ }
159
+
160
+ /**
161
+ * Get all values in cache (for debugging)
162
+ */
163
+ values() {
164
+ const values = [];
165
+ let node = this.head.next;
166
+
167
+ while (node !== this.tail) {
168
+ if (!this._isExpired(node)) {
169
+ values.push(node.value);
170
+ }
171
+ node = node.next;
172
+ }
173
+
174
+ return values;
175
+ }
176
+
177
+ /**
178
+ * Get cache statistics
179
+ */
180
+ getStats() {
181
+ const hitRate = this.stats.hits + this.stats.misses > 0
182
+ ? (this.stats.hits / (this.stats.hits + this.stats.misses) * 100).toFixed(2)
183
+ : 0;
184
+
185
+ return {
186
+ ...this.stats,
187
+ hitRate: `${hitRate}%`,
188
+ size: this.cache.size,
189
+ maxSize: this.options.maxSize,
190
+ utilization: `${((this.cache.size / this.options.maxSize) * 100).toFixed(1)}%`
191
+ };
192
+ }
193
+
194
+ /**
195
+ * Move node to front of LRU list
196
+ */
197
+ _moveToFront(node) {
198
+ // Remove from current position
199
+ this._removeNode(node);
200
+
201
+ // Insert after head
202
+ node.prev = this.head;
203
+ node.next = this.head.next;
204
+ this.head.next.prev = node;
205
+ this.head.next = node;
206
+ }
207
+
208
+ /**
209
+ * Remove node from linked list
210
+ */
211
+ _removeNode(node) {
212
+ node.prev.next = node.next;
213
+ node.next.prev = node.prev;
214
+ }
215
+
216
+ /**
217
+ * Evict least recently used item
218
+ */
219
+ _evictLRU() {
220
+ const lruNode = this.tail.prev;
221
+
222
+ if (lruNode !== this.head) {
223
+ this._removeNode(lruNode);
224
+ this.cache.delete(lruNode.key);
225
+ this.stats.evictions++;
226
+ this._updateMemoryStats();
227
+ }
228
+ }
229
+
230
+ /**
231
+ * Check if node has expired
232
+ */
233
+ _isExpired(node) {
234
+ return Date.now() > node.expires;
235
+ }
236
+
237
+ /**
238
+ * Start periodic cleanup of expired items
239
+ */
240
+ _startCleanupInterval() {
241
+ setInterval(() => {
242
+ this._cleanupExpired();
243
+ }, this.options.cleanupInterval);
244
+ }
245
+
246
+ /**
247
+ * Remove all expired items from cache
248
+ */
249
+ _cleanupExpired() {
250
+ const now = Date.now();
251
+ let node = this.head.next;
252
+ let expiredCount = 0;
253
+
254
+ while (node !== this.tail) {
255
+ const nextNode = node.next;
256
+
257
+ if (now > node.expires) {
258
+ this._removeNode(node);
259
+ this.cache.delete(node.key);
260
+ expiredCount++;
261
+ }
262
+
263
+ node = nextNode;
264
+ }
265
+
266
+ if (expiredCount > 0 && this.options.debug) {
267
+ console.log(`๐Ÿงน Cache cleanup: removed ${expiredCount} expired items`);
268
+ }
269
+
270
+ this._updateMemoryStats();
271
+ }
272
+
273
+ /**
274
+ * Estimate memory usage (rough calculation)
275
+ */
276
+ _updateMemoryStats() {
277
+ let totalSize = 0;
278
+
279
+ for (const [key, node] of this.cache) {
280
+ // Rough estimation: key size + value size (stringify for simplicity)
281
+ totalSize += Buffer.byteLength(key, 'utf8');
282
+ totalSize += Buffer.byteLength(JSON.stringify(node.value), 'utf8');
283
+ }
284
+
285
+ this.stats.memoryUsage = totalSize;
286
+ }
287
+
288
+ /**
289
+ * Pre-warm cache with data
290
+ */
291
+ async warmup(dataMap, ttl = this.options.ttl) {
292
+ for (const [key, value] of Object.entries(dataMap)) {
293
+ this.set(key, value, ttl);
294
+ }
295
+
296
+ if (this.options.debug) {
297
+ console.log(`๐Ÿ”ฅ Cache warmup complete: ${Object.keys(dataMap).length} items`);
298
+ }
299
+ }
300
+
301
+ /**
302
+ * Get cache snapshot for debugging
303
+ */
304
+ getSnapshot() {
305
+ const snapshot = {};
306
+ let node = this.head.next;
307
+
308
+ while (node !== this.tail) {
309
+ if (!this._isExpired(node)) {
310
+ snapshot[node.key] = {
311
+ value: node.value,
312
+ expiresIn: node.expires - Date.now(),
313
+ ttl: this.options.ttl
314
+ };
315
+ }
316
+ node = node.next;
317
+ }
318
+
319
+ return snapshot;
320
+ }
321
+
322
+ /**
323
+ * Resize cache (useful for dynamic memory management)
324
+ */
325
+ resize(newSize) {
326
+ this.options.maxSize = newSize;
327
+
328
+ // Evict excess items if needed
329
+ while (this.cache.size > newSize) {
330
+ this._evictLRU();
331
+ }
332
+
333
+ if (this.options.debug) {
334
+ console.log(`๐Ÿ“ Cache resized: ${newSize} items`);
335
+ }
336
+ }
337
+ }
338
+
339
+ module.exports = Cache;
@@ -0,0 +1,355 @@
1
+ /**
2
+ * LazyLoader - Loads data only when needed, saves memory like a boss ๐Ÿ’พ
3
+ *
4
+ * Why load everything when you only need some things?
5
+ * This made our memory usage drop faster than my grades in college ๐Ÿ˜…
6
+ */
7
+
8
+ class LazyLoader {
9
+ constructor(storage, options = {}) {
10
+ this.storage = storage;
11
+ this.options = {
12
+ chunkSize: 100, // Items per chunk
13
+ prefetch: true, // Load next chunk in background
14
+ maxLoadedChunks: 5, // Keep this many chunks in memory
15
+ autoUnload: true, // Unload old chunks automatically
16
+ ...options
17
+ };
18
+
19
+ // Chunk management
20
+ this.chunks = new Map(); // chunkIndex -> data
21
+ this.chunkIndex = new Map(); // key -> chunkIndex
22
+ this.accessHistory = []; // LRU for chunks
23
+ this.loadedChunksCount = 0;
24
+
25
+ // Performance tracking
26
+ this.stats = {
27
+ chunksLoaded: 0,
28
+ chunksUnloaded: 0,
29
+ keysLoaded: 0,
30
+ memorySaved: 0,
31
+ cacheHits: 0,
32
+ cacheMisses: 0,
33
+ prefetchHits: 0
34
+ };
35
+
36
+ this._initialized = false;
37
+ }
38
+
39
+ /**
40
+ * Initialize the lazy loader - build chunk index
41
+ */
42
+ async initialize(allKeys) {
43
+ if (this._initialized) return;
44
+
45
+ // Build chunk index from all keys
46
+ let chunkIndex = 0;
47
+ let currentChunkSize = 0;
48
+
49
+ for (const key of allKeys) {
50
+ this.chunkIndex.set(key, chunkIndex);
51
+ currentChunkSize++;
52
+
53
+ if (currentChunkSize >= this.options.chunkSize) {
54
+ chunkIndex++;
55
+ currentChunkSize = 0;
56
+ }
57
+ }
58
+
59
+ this.totalChunks = chunkIndex + 1;
60
+ this._initialized = true;
61
+
62
+ if (this.options.debug) {
63
+ console.log(`๐Ÿ“Š LazyLoader: ${allKeys.length} keys in ${this.totalChunks} chunks`);
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Get value by key - loads chunk if needed
69
+ */
70
+ async get(key) {
71
+ if (!this._initialized) {
72
+ throw new Error('LazyLoader not initialized. Call initialize() first.');
73
+ }
74
+
75
+ const chunkIndex = this.chunkIndex.get(key);
76
+
77
+ if (chunkIndex === undefined) {
78
+ this.stats.cacheMisses++;
79
+ return undefined; // Key not found
80
+ }
81
+
82
+ // Check if chunk is already loaded
83
+ if (this.chunks.has(chunkIndex)) {
84
+ this.stats.cacheHits++;
85
+ this._updateAccessHistory(chunkIndex);
86
+ return this.chunks.get(chunkIndex).get(key);
87
+ }
88
+
89
+ this.stats.cacheMisses++;
90
+
91
+ // Load the chunk
92
+ await this._loadChunk(chunkIndex);
93
+
94
+ // Prefetch adjacent chunks in background
95
+ if (this.options.prefetch) {
96
+ this._prefetchAdjacentChunks(chunkIndex);
97
+ }
98
+
99
+ const chunk = this.chunks.get(chunkIndex);
100
+ return chunk ? chunk.get(key) : undefined;
101
+ }
102
+
103
+ /**
104
+ * Set value - updates chunk if loaded, or defers to storage
105
+ */
106
+ async set(key, value) {
107
+ const chunkIndex = this.chunkIndex.get(key);
108
+
109
+ if (chunkIndex !== undefined && this.chunks.has(chunkIndex)) {
110
+ // Update in loaded chunk
111
+ this.chunks.get(chunkIndex).set(key, value);
112
+ this._updateAccessHistory(chunkIndex);
113
+ }
114
+
115
+ // Always update in storage
116
+ await this.storage.set(key, value);
117
+ }
118
+
119
+ /**
120
+ * Check if key exists (without loading chunk)
121
+ */
122
+ has(key) {
123
+ return this.chunkIndex.has(key);
124
+ }
125
+
126
+ /**
127
+ * Get all keys (without loading data)
128
+ */
129
+ getAllKeys() {
130
+ return Array.from(this.chunkIndex.keys());
131
+ }
132
+
133
+ /**
134
+ * Load a specific chunk into memory
135
+ */
136
+ async _loadChunk(chunkIndex) {
137
+ // Unload least recently used chunks if we're at the limit
138
+ if (this.loadedChunksCount >= this.options.maxLoadedChunks) {
139
+ await this._unloadLRUChunk();
140
+ }
141
+
142
+ // Get all keys in this chunk
143
+ const chunkKeys = [];
144
+ for (const [key, index] of this.chunkIndex) {
145
+ if (index === chunkIndex) {
146
+ chunkKeys.push(key);
147
+ }
148
+ }
149
+
150
+ // Load data for these keys
151
+ const chunkData = new Map();
152
+ for (const key of chunkKeys) {
153
+ const value = await this.storage.get(key);
154
+ if (value !== undefined) {
155
+ chunkData.set(key, value);
156
+ }
157
+ }
158
+
159
+ // Store the chunk
160
+ this.chunks.set(chunkIndex, chunkData);
161
+ this._updateAccessHistory(chunkIndex);
162
+ this.loadedChunksCount++;
163
+ this.stats.chunksLoaded++;
164
+ this.stats.keysLoaded += chunkData.size;
165
+
166
+ if (this.options.debug) {
167
+ console.log(`๐Ÿ“ Loaded chunk ${chunkIndex} with ${chunkData.size} items`);
168
+ }
169
+
170
+ return chunkData;
171
+ }
172
+
173
+ /**
174
+ * Unload least recently used chunk
175
+ */
176
+ async _unloadLRUChunk() {
177
+ if (this.accessHistory.length === 0) return;
178
+
179
+ const lruChunkIndex = this.accessHistory[0];
180
+ await this._unloadChunk(lruChunkIndex);
181
+ }
182
+
183
+ /**
184
+ * Unload specific chunk
185
+ */
186
+ async _unloadChunk(chunkIndex) {
187
+ const chunk = this.chunks.get(chunkIndex);
188
+ if (!chunk) return;
189
+
190
+ // Calculate memory saved (rough estimate)
191
+ let chunkSize = 0;
192
+ for (const [key, value] of chunk) {
193
+ chunkSize += this._estimateSize(key) + this._estimateSize(value);
194
+ }
195
+
196
+ this.chunks.delete(chunkIndex);
197
+ this.accessHistory = this.accessHistory.filter(idx => idx !== chunkIndex);
198
+ this.loadedChunksCount--;
199
+ this.stats.chunksUnloaded++;
200
+ this.stats.memorySaved += chunkSize;
201
+
202
+ if (this.options.debug) {
203
+ console.log(`๐Ÿ—‘๏ธ Unloaded chunk ${chunkIndex} (saved ~${chunkSize} bytes)`);
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Prefetch chunks around the currently loaded one
209
+ */
210
+ _prefetchAdjacentChunks(currentChunkIndex) {
211
+ const prefetchIndices = [
212
+ currentChunkIndex + 1, // Next chunk
213
+ currentChunkIndex - 1 // Previous chunk
214
+ ].filter(index => index >= 0 && index < this.totalChunks && !this.chunks.has(index));
215
+
216
+ // Prefetch in background (don't await)
217
+ for (const index of prefetchIndices) {
218
+ this._loadChunk(index).then(() => {
219
+ this.stats.prefetchHits++;
220
+ }).catch(error => {
221
+ console.error(`Prefetch failed for chunk ${index}:`, error);
222
+ });
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Update access history for LRU tracking
228
+ */
229
+ _updateAccessHistory(chunkIndex) {
230
+ // Remove existing entry
231
+ this.accessHistory = this.accessHistory.filter(idx => idx !== chunkIndex);
232
+ // Add to end (most recently used)
233
+ this.accessHistory.push(chunkIndex);
234
+ }
235
+
236
+ /**
237
+ * Estimate size of an object in bytes
238
+ */
239
+ _estimateSize(obj) {
240
+ if (obj === null || obj === undefined) return 0;
241
+
242
+ switch (typeof obj) {
243
+ case 'string':
244
+ return obj.length * 2; // 2 bytes per character
245
+ case 'number':
246
+ return 8; // 8 bytes for number
247
+ case 'boolean':
248
+ return 4; // 4 bytes for boolean
249
+ case 'object':
250
+ if (Array.isArray(obj)) {
251
+ return obj.reduce((size, item) => size + this._estimateSize(item), 0);
252
+ } else {
253
+ let size = 0;
254
+ for (const key in obj) {
255
+ if (obj.hasOwnProperty(key)) {
256
+ size += this._estimateSize(key) + this._estimateSize(obj[key]);
257
+ }
258
+ }
259
+ return size;
260
+ }
261
+ default:
262
+ return 0;
263
+ }
264
+ }
265
+
266
+ /**
267
+ * Manually load a chunk (for eager loading)
268
+ */
269
+ async loadChunk(chunkIndex) {
270
+ return await this._loadChunk(chunkIndex);
271
+ }
272
+
273
+ /**
274
+ * Manually unload a chunk
275
+ */
276
+ async unloadChunk(chunkIndex) {
277
+ return await this._unloadChunk(chunkIndex);
278
+ }
279
+
280
+ /**
281
+ * Get currently loaded chunks
282
+ */
283
+ getLoadedChunks() {
284
+ return Array.from(this.chunks.keys());
285
+ }
286
+
287
+ /**
288
+ * Get chunk information for a key
289
+ */
290
+ getChunkInfo(key) {
291
+ const chunkIndex = this.chunkIndex.get(key);
292
+ if (chunkIndex === undefined) return null;
293
+
294
+ const isLoaded = this.chunks.has(chunkIndex);
295
+ const keysInChunk = Array.from(this.chunkIndex.entries())
296
+ .filter(([k, idx]) => idx === chunkIndex)
297
+ .map(([k]) => k);
298
+
299
+ return {
300
+ chunkIndex,
301
+ isLoaded,
302
+ keysInChunk,
303
+ loadedChunks: this.loadedChunksCount,
304
+ totalChunks: this.totalChunks
305
+ };
306
+ }
307
+
308
+ /**
309
+ * Get performance statistics
310
+ */
311
+ getStats() {
312
+ const totalAccesses = this.stats.cacheHits + this.stats.cacheMisses;
313
+ const hitRate = totalAccesses > 0
314
+ ? (this.stats.cacheHits / totalAccesses * 100).toFixed(2)
315
+ : 0;
316
+
317
+ return {
318
+ ...this.stats,
319
+ hitRate: `${hitRate}%`,
320
+ loadedChunks: this.loadedChunksCount,
321
+ totalChunks: this.totalChunks,
322
+ memorySaved: `${(this.stats.memorySaved / 1024 / 1024).toFixed(2)} MB`,
323
+ prefetchEffectiveness: this.stats.prefetchHits > 0
324
+ ? `${((this.stats.prefetchHits / this.stats.chunksLoaded) * 100).toFixed(1)}%`
325
+ : '0%'
326
+ };
327
+ }
328
+
329
+ /**
330
+ * Clear all loaded chunks
331
+ */
332
+ clear() {
333
+ this.chunks.clear();
334
+ this.accessHistory = [];
335
+ this.loadedChunksCount = 0;
336
+
337
+ if (this.options.debug) {
338
+ console.log('๐Ÿงน Cleared all loaded chunks');
339
+ }
340
+ }
341
+
342
+ /**
343
+ * Preload specific chunks (for startup optimization)
344
+ */
345
+ async preloadChunks(chunkIndices) {
346
+ const loadPromises = chunkIndices.map(index => this._loadChunk(index));
347
+ await Promise.all(loadPromises);
348
+
349
+ if (this.options.debug) {
350
+ console.log(`๐Ÿ”ฅ Preloaded ${chunkIndices.length} chunks`);
351
+ }
352
+ }
353
+ }
354
+
355
+ module.exports = LazyLoader;