import { mcpDb } from './supabase.js';
import { rateLimiters } from '../utils/rate-limiter.js';
import { createLogger } from '../utils/logger.js';
const logger = createLogger({ module: 'rate-limited-db' });
/**
* Wraps Supabase client methods with rate limiting
*/
export function createRateLimitedClient(client: typeof mcpDb) {
// Create a proxy to intercept method calls
return new Proxy(client, {
get(target, prop) {
const original = target[prop as keyof typeof target];
// Only wrap the 'from' and 'rpc' methods
if (prop === 'from') {
return function (...args: any[]) {
const query = (original as any).apply(target, args);
// Wrap the query execution methods
const wrapMethod = (method: string) => {
const originalMethod = query[method];
if (typeof originalMethod === 'function') {
query[method] = function (...methodArgs: any[]) {
const result = originalMethod.apply(query, methodArgs);
// If it returns a promise-like object with 'then', wrap it
if (result && typeof result.then === 'function') {
const originalThen = result.then.bind(result);
result.then = function (onfulfilled?: any, onrejected?: any) {
return rateLimiters.supabase.executeWithRateLimit(
() => originalThen(onfulfilled, onrejected),
{
priority: method === 'insert' || method === 'update' ? 'high' : 'normal'
}
);
};
}
return result;
};
}
};
// Wrap common query methods
['select', 'insert', 'update', 'delete', 'upsert'].forEach(wrapMethod);
return query;
};
}
if (prop === 'rpc') {
return function (...args: any[]) {
return rateLimiters.supabase.executeWithRateLimit(
() => (original as any).apply(target, args),
{ priority: 'normal' }
);
};
}
// Return original for other properties
if (typeof original === 'function') {
return original.bind(target);
}
return original;
}
});
}
// Export rate-limited version of mcpDb
export const rateLimitedMcpDb = createRateLimitedClient(mcpDb);
// Log initialization
logger.info('Rate-limited database client initialized', {
limits: {
maxRequests: 500,
windowMs: 60000,
maxConcurrent: 20
}
});