-
-
Notifications
You must be signed in to change notification settings - Fork 8.1k
Add SQLite caching with --no-cache and --force-check flags (#2219) #2608
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
obiwan04kanobi
wants to merge
5
commits into
sherlock-project:master
Choose a base branch
from
obiwan04kanobi:feature/2219-sqlite-caching
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+883
−2
Open
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f82cf61
feat: add SQLite caching with cache management utilities
obiwan04kanobi 2b1aaeb
fix: remove unused json import from cache.py
obiwan04kanobi d3425f2
Merge branch 'sherlock-project:master' into feature/2219-sqlite-caching
obiwan04kanobi 4b32a07
fix: address all security and code quality issues from PR review
obiwan04kanobi e6b6f04
Removing tox from pyproject.toml
obiwan04kanobi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,181 @@ | ||
""" | ||
Sherlock Cache Module | ||
This module handles SQLite-based caching for username lookup results. | ||
""" | ||
|
||
import sqlite3 | ||
import time | ||
from pathlib import Path | ||
from typing import Optional, Dict, Any | ||
from sherlock_project.result import QueryStatus | ||
obiwan04kanobi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
|
||
class SherlockCache: | ||
"""Manages SQLite cache for Sherlock results.""" | ||
|
||
def __init__(self, cache_path: Optional[str] = None, cache_duration: int = 86400): | ||
""" | ||
Initialize the cache. | ||
Args: | ||
cache_path: Path to SQLite database file. Defaults to ~/.sherlock_cache.db | ||
cache_duration: Time in seconds to cache results. Default: 86400 (24 hours) | ||
""" | ||
if cache_path is None: | ||
cache_dir = Path.home() / ".sherlock" | ||
obiwan04kanobi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
cache_dir.mkdir(exist_ok=True) | ||
cache_path = str(cache_dir / "cache.db") | ||
|
||
self.cache_path = cache_path | ||
self.cache_duration = cache_duration | ||
self._init_database() | ||
|
||
def _init_database(self): | ||
"""Initialize the SQLite database with required tables.""" | ||
conn = sqlite3.connect(self.cache_path) | ||
cursor = conn.cursor() | ||
|
||
cursor.execute(''' | ||
CREATE TABLE IF NOT EXISTS results ( | ||
username TEXT NOT NULL, | ||
site TEXT NOT NULL, | ||
status TEXT NOT NULL, | ||
url TEXT, | ||
timestamp INTEGER NOT NULL, | ||
PRIMARY KEY (username, site) | ||
) | ||
''') | ||
|
||
# Create index for faster lookups | ||
cursor.execute(''' | ||
CREATE INDEX IF NOT EXISTS idx_timestamp | ||
ON results(timestamp) | ||
''') | ||
|
||
conn.commit() | ||
conn.close() | ||
|
||
def get(self, username: str, site: str) -> Optional[Dict[str, Any]]: | ||
obiwan04kanobi marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
""" | ||
Retrieve cached result for a username on a specific site. | ||
Args: | ||
username: The username to lookup | ||
site: The site name | ||
Returns: | ||
Dictionary with cached result or None if not cached/expired | ||
""" | ||
conn = sqlite3.connect(self.cache_path) | ||
cursor = conn.cursor() | ||
|
||
cursor.execute(''' | ||
SELECT status, url, timestamp FROM results | ||
WHERE username = ? AND site = ? | ||
''', (username, site)) | ||
|
||
result = cursor.fetchone() | ||
conn.close() | ||
|
||
if result is None: | ||
return None | ||
|
||
status, url, timestamp = result | ||
current_time = int(time.time()) | ||
|
||
# Check if cache is expired | ||
if current_time - timestamp > self.cache_duration: | ||
return None | ||
|
||
return { | ||
'status': QueryStatus[status], | ||
'url': url, | ||
'timestamp': timestamp | ||
} | ||
|
||
def set(self, username: str, site: str, status: QueryStatus, | ||
url: Optional[str] = None): | ||
""" | ||
Store result in cache. | ||
Args: | ||
username: The username | ||
site: The site name | ||
status: Query status | ||
url: URL of the found profile (if applicable) | ||
""" | ||
conn = sqlite3.connect(self.cache_path) | ||
cursor = conn.cursor() | ||
|
||
current_time = int(time.time()) | ||
|
||
cursor.execute(''' | ||
INSERT OR REPLACE INTO results (username, site, status, url, timestamp) | ||
VALUES (?, ?, ?, ?, ?) | ||
''', (username, site, status.name, url, current_time)) | ||
|
||
conn.commit() | ||
conn.close() | ||
|
||
def clear(self, username: Optional[str] = None, site: Optional[str] = None): | ||
""" | ||
Clear cache entries. | ||
Args: | ||
username: Clear specific username (if None, clears all) | ||
site: Clear specific site (if None, clears all) | ||
""" | ||
conn = sqlite3.connect(self.cache_path) | ||
cursor = conn.cursor() | ||
|
||
if username and site: | ||
cursor.execute('DELETE FROM results WHERE username = ? AND site = ?', | ||
(username, site)) | ||
elif username: | ||
cursor.execute('DELETE FROM results WHERE username = ?', (username,)) | ||
elif site: | ||
cursor.execute('DELETE FROM results WHERE site = ?', (site,)) | ||
else: | ||
cursor.execute('DELETE FROM results') | ||
|
||
conn.commit() | ||
conn.close() | ||
|
||
def cleanup_expired(self): | ||
"""Remove expired entries from cache.""" | ||
conn = sqlite3.connect(self.cache_path) | ||
cursor = conn.cursor() | ||
|
||
current_time = int(time.time()) | ||
expiration_time = current_time - self.cache_duration | ||
obiwan04kanobi marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
cursor.execute('DELETE FROM results WHERE timestamp < ?', | ||
(expiration_time,)) | ||
|
||
conn.commit() | ||
conn.close() | ||
|
||
def get_stats(self) -> Dict[str, Any]: | ||
"""Get cache statistics.""" | ||
conn = sqlite3.connect(self.cache_path) | ||
cursor = conn.cursor() | ||
|
||
cursor.execute('SELECT COUNT(*) FROM results') | ||
total = cursor.fetchone()[0] | ||
|
||
current_time = int(time.time()) | ||
expiration_time = current_time - self.cache_duration | ||
|
||
cursor.execute('SELECT COUNT(*) FROM results WHERE timestamp >= ?', | ||
(expiration_time,)) | ||
valid = cursor.fetchone()[0] | ||
|
||
conn.close() | ||
|
||
return { | ||
'total_entries': total, | ||
'valid_entries': valid, | ||
'expired_entries': total - valid, | ||
'cache_path': self.cache_path | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
#!/usr/bin/env python3 | ||
""" | ||
Sherlock Cache Management CLI | ||
Utility for managing Sherlock's SQLite cache. | ||
""" | ||
|
||
import argparse | ||
import sys | ||
from sherlock_project.cache import SherlockCache | ||
obiwan04kanobi marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
from colorama import Fore, Style | ||
|
||
|
||
def main(): | ||
"""Main entry point for cache management CLI.""" | ||
parser = argparse.ArgumentParser( | ||
prog="sherlock-cache", | ||
description="Manage Sherlock's result cache" | ||
) | ||
|
||
subparsers = parser.add_subparsers(dest="command", help="Cache management commands") | ||
|
||
# Clear command | ||
clear_parser = subparsers.add_parser("clear", help="Clear cache entries") | ||
clear_parser.add_argument( | ||
"--username", | ||
help="Clear cache for specific username only" | ||
) | ||
clear_parser.add_argument( | ||
"--site", | ||
help="Clear cache for specific site only" | ||
) | ||
|
||
# Stats command | ||
subparsers.add_parser("stats", help="Show cache statistics") | ||
|
||
# Cleanup command | ||
subparsers.add_parser("cleanup", help="Remove expired cache entries") | ||
|
||
args = parser.parse_args() | ||
|
||
if not args.command: | ||
parser.print_help() | ||
sys.exit(1) | ||
|
||
cache = SherlockCache() | ||
|
||
if args.command == "clear": | ||
username = getattr(args, 'username', None) | ||
site = getattr(args, 'site', None) | ||
|
||
cache.clear(username=username, site=site) | ||
|
||
if username and site: | ||
print(f"{Fore.GREEN}✓{Style.RESET_ALL} Cleared cache for {username} on {site}") | ||
elif username: | ||
print(f"{Fore.GREEN}✓{Style.RESET_ALL} Cleared all cache for username: {username}") | ||
elif site: | ||
print(f"{Fore.GREEN}✓{Style.RESET_ALL} Cleared all cache for site: {site}") | ||
else: | ||
print(f"{Fore.GREEN}✓{Style.RESET_ALL} Cleared entire cache") | ||
|
||
elif args.command == "stats": | ||
stats = cache.get_stats() | ||
print(f"\n{Style.BRIGHT}Cache Statistics:{Style.RESET_ALL}") | ||
print(f" Cache Path: {stats['cache_path']}") | ||
print(f" Total Entries: {stats['total_entries']}") | ||
print(f" Valid Entries: {Fore.GREEN}{stats['valid_entries']}{Style.RESET_ALL}") | ||
print(f" Expired Entries: {Fore.YELLOW}{stats['expired_entries']}{Style.RESET_ALL}\n") | ||
|
||
elif args.command == "cleanup": | ||
cache.cleanup_expired() | ||
print(f"{Fore.GREEN}✓{Style.RESET_ALL} Cleaned up expired cache entries") | ||
|
||
|
||
if __name__ == "__main__": | ||
main() | ||
obiwan04kanobi marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Bikeshed:
Could we do
--skip-cache
and--ignore-cache
? I feel like that just removes some ambiguity.Like, what does --force-check even do? Of course I want to check these usernames. Maybe it bypasses username validation? (of course we know what it does)
Open to hearing your thoughts.