Repository navigation
refactor(db): move usage_logs/semantic_cache/proxy_logs SQL into db modules (#3500 slice 4) #3648
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
Merged
Merged
Changes from all commits
Commits
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
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
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,35 @@ | ||
| /** | ||
| * db/proxyLogs.ts — Read queries over the `proxy_logs` table. | ||
| * Extracted from the /api/logs/export route handler. | ||
| * | ||
| * Hard Rule #5: routes must not embed raw SQL — these queries live here so the | ||
| * /api/logs/export route can delegate. | ||
| * | ||
| * NOTE: The SELECT * intentionally returns the historical `public_ip` column, | ||
| * NOT `clientIp`. This differs from GET /api/usage/proxy-logs which exposes | ||
| * the value as `clientIp`. Callers of the export endpoint should read | ||
| * `public_ip`. This inconsistency will be resolved in a future DB migration | ||
| * (#2880). | ||
| * | ||
| * Sliced out of #3500 (proxy_logs cluster, slice 4). | ||
| */ | ||
|
|
||
| import { getDbInstance } from "./core"; | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Queries | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| /** | ||
| * Returns all proxy_logs rows with timestamp >= `since`, ordered by timestamp | ||
| * descending (most recent first). | ||
| * | ||
| * @param since - ISO-8601 timestamp lower bound, e.g. "2024-01-01T00:00:00.000Z". | ||
| */ | ||
| export function exportProxyLogsSince(since: string): Record<string, unknown>[] { | ||
| const db = getDbInstance(); | ||
| const stmt = db.prepare( | ||
| "SELECT * FROM proxy_logs WHERE timestamp >= @since ORDER BY timestamp DESC" | ||
| ); | ||
| return stmt.all({ since }) as Record<string, unknown>[]; | ||
| } |
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,117 @@ | ||||||||||
| /** | ||||||||||
| * db/semanticCache.ts — CRUD queries over the `semantic_cache` table. | ||||||||||
| * Extracted from the /api/cache/entries route handler. | ||||||||||
| * | ||||||||||
| * Hard Rule #5: routes must not embed raw SQL — these queries live here so the | ||||||||||
| * /api/cache/entries route can delegate. | ||||||||||
| * | ||||||||||
| * Sliced out of #3500 (semantic_cache cluster, slice 4). | ||||||||||
| */ | ||||||||||
|
|
||||||||||
| import { getDbInstance } from "./core"; | ||||||||||
|
|
||||||||||
| // --------------------------------------------------------------------------- | ||||||||||
| // Shared types | ||||||||||
| // --------------------------------------------------------------------------- | ||||||||||
|
|
||||||||||
| export interface SemanticCacheEntry { | ||||||||||
| id: string; | ||||||||||
| signature: string; | ||||||||||
| model: string; | ||||||||||
| hit_count: number; | ||||||||||
| tokens_saved: number; | ||||||||||
| created_at: string; | ||||||||||
| expires_at: string; | ||||||||||
| } | ||||||||||
|
|
||||||||||
| export interface SemanticCacheListOptions { | ||||||||||
| page: number; | ||||||||||
| limit: number; | ||||||||||
| search: string; | ||||||||||
| model: string; | ||||||||||
| sortBy: string; | ||||||||||
| sortOrder: string; | ||||||||||
| } | ||||||||||
|
|
||||||||||
| export interface SemanticCacheListResult { | ||||||||||
| entries: SemanticCacheEntry[]; | ||||||||||
| total: number; | ||||||||||
| } | ||||||||||
|
|
||||||||||
| // --------------------------------------------------------------------------- | ||||||||||
| // Queries | ||||||||||
| // --------------------------------------------------------------------------- | ||||||||||
|
|
||||||||||
| const VALID_SORT_COLUMNS = ["created_at", "expires_at", "hit_count", "tokens_saved", "model"]; | ||||||||||
|
|
||||||||||
| /** | ||||||||||
| * Returns a paginated, filtered, sorted list of semantic cache entries. | ||||||||||
| * All dynamic inputs (sortBy/sortOrder) are validated before use. | ||||||||||
| */ | ||||||||||
| export function listSemanticCacheEntries(opts: SemanticCacheListOptions): SemanticCacheListResult { | ||||||||||
| const db = getDbInstance(); | ||||||||||
| const { page, limit, search, model, sortBy, sortOrder } = opts; | ||||||||||
| const offset = (page - 1) * limit; | ||||||||||
|
|
||||||||||
| const conditions: string[] = []; | ||||||||||
| const params: unknown[] = []; | ||||||||||
|
|
||||||||||
| if (search) { | ||||||||||
| conditions.push("(signature LIKE ? OR model LIKE ?)"); | ||||||||||
| params.push(`%${search}%`, `%${search}%`); | ||||||||||
| } | ||||||||||
|
|
||||||||||
| if (model) { | ||||||||||
| conditions.push("model = ?"); | ||||||||||
| params.push(model); | ||||||||||
| } | ||||||||||
|
|
||||||||||
| const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : ""; | ||||||||||
| const orderBy = VALID_SORT_COLUMNS.includes(sortBy) ? sortBy : "created_at"; | ||||||||||
| const order = sortOrder === "asc" ? "ASC" : "DESC"; | ||||||||||
|
|
||||||||||
| const countRow = db | ||||||||||
| .prepare(`SELECT COUNT(*) as total FROM semantic_cache ${whereClause}`) | ||||||||||
| .get(...params) as { total: number }; | ||||||||||
|
|
||||||||||
| const entries = db | ||||||||||
| .prepare( | ||||||||||
| `SELECT id, signature, model, hit_count, tokens_saved, created_at, expires_at | ||||||||||
| FROM semantic_cache ${whereClause} | ||||||||||
| ORDER BY ${orderBy} ${order} | ||||||||||
| LIMIT ? OFFSET ?` | ||||||||||
| ) | ||||||||||
| .all(...params, limit, offset) as SemanticCacheEntry[]; | ||||||||||
|
|
||||||||||
| return { entries, total: countRow?.total || 0 }; | ||||||||||
| } | ||||||||||
|
|
||||||||||
| export interface DeleteSemanticCacheBySignatureResult { | ||||||||||
| deleted: number; | ||||||||||
| } | ||||||||||
|
|
||||||||||
| /** | ||||||||||
| * Deletes the single semantic cache entry matching the given signature. | ||||||||||
| * Returns `{ deleted: 1 }` on success. | ||||||||||
| */ | ||||||||||
| export function deleteSemanticCacheBySignature( | ||||||||||
| signature: string | ||||||||||
| ): DeleteSemanticCacheBySignatureResult { | ||||||||||
| const db = getDbInstance(); | ||||||||||
| db.prepare("DELETE FROM semantic_cache WHERE signature = ?").run(signature); | ||||||||||
| return { deleted: 1 }; | ||||||||||
|
Comment on lines
+101
to
+102
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In
Suggested change
|
||||||||||
| } | ||||||||||
|
|
||||||||||
| export interface DeleteSemanticCacheByModelResult { | ||||||||||
| deleted: number; | ||||||||||
| } | ||||||||||
|
|
||||||||||
| /** | ||||||||||
| * Deletes all semantic cache entries for the given model. | ||||||||||
| * Returns `{ deleted: N }` where N is the number of rows removed. | ||||||||||
| */ | ||||||||||
| export function deleteSemanticCacheByModel(model: string): DeleteSemanticCacheByModelResult { | ||||||||||
| const db = getDbInstance(); | ||||||||||
| const result = db.prepare("DELETE FROM semantic_cache WHERE model = ?").run(model); | ||||||||||
| return { deleted: result.changes }; | ||||||||||
| } | ||||||||||
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.
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.
If
opts.pageoropts.limitare parsed asNaNor negative values at runtime, it can lead to invalid SQL queries or unexpected offset calculations. Adding defensive guards usingMath.maxandisNaNchecks ensures the pagination parameters are always valid positive integers.