Spaces:
Paused
Paused
Upload 3 files
Browse filesFiles changed (3)
- src/db.tsAdded+127
- src/rate-limiter.tsAdded+43
- src/review.ts+31-25
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127import postgres from 'postgres'
const sql = postgres(process.env.DATABASE_URL!, { max: 10, idle_timeout: 20, connect_timeout: 10, transform: { undefined: null, },})
export { sql }
export async function initializeDatabase() { try { await sql` CREATE TABLE IF NOT EXISTS users ( id VARCHAR(50) PRIMARY KEY, github_id INTEGER UNIQUE NOT NULL, username VARCHAR(100) NOT NULL, email VARCHAR(255) UNIQUE, avatar_url TEXT, plan VARCHAR(20) DEFAULT 'free', created_at TIMESTAMP DEFAULT NOW(), updated_at TIMESTAMP DEFAULT NOW() ) `
await sql` CREATE TABLE IF NOT EXISTS user_events ( id SERIAL PRIMARY KEY, event_type VARCHAR(50) NOT NULL, user_id VARCHAR(100), session_id VARCHAR(100) NOT NULL, page_url TEXT, referrer TEXT, user_agent TEXT, ip_hash VARCHAR(64), metadata JSONB, created_at TIMESTAMP DEFAULT NOW() ) `
await sql` CREATE TABLE IF NOT EXISTS revenue_events ( id SERIAL PRIMARY KEY, event_type VARCHAR(50) NOT NULL, amount DECIMAL(10, 2) NOT NULL, currency VARCHAR(3) DEFAULT 'USD', customer_id VARCHAR(100), github_id INTEGER, subscription_tier VARCHAR(20), metadata JSONB, created_at TIMESTAMP DEFAULT NOW() ) `
await sql` CREATE TABLE IF NOT EXISTS affiliate_users ( id VARCHAR(100) PRIMARY KEY, github_id INTEGER UNIQUE NOT NULL, username VARCHAR(100) NOT NULL, affiliate_code VARCHAR(50) UNIQUE NOT NULL, referral_count INTEGER DEFAULT 0, paid_referral_count INTEGER DEFAULT 0, tier VARCHAR(20) DEFAULT 'free', created_at TIMESTAMP DEFAULT NOW() ) `
await sql` CREATE TABLE IF NOT EXISTS referrals ( id VARCHAR(100) PRIMARY KEY, affiliate_id VARCHAR(100) NOT NULL REFERENCES affiliate_users(id), referred_github_id INTEGER UNIQUE NOT NULL, referred_username VARCHAR(100) NOT NULL, referred_ip_hash VARCHAR(64) NOT NULL, has_purchased BOOLEAN DEFAULT FALSE, created_at TIMESTAMP DEFAULT NOW() ) `
await sql` CREATE TABLE IF NOT EXISTS affiliate_events ( id SERIAL PRIMARY KEY, event_type VARCHAR(50) NOT NULL, affiliate_id VARCHAR(100) NOT NULL, affiliate_code VARCHAR(50), referrer_id VARCHAR(100), commission_amount DECIMAL(10, 2) DEFAULT 0, conversion_status VARCHAR(20) DEFAULT 'pending', metadata JSONB, created_at TIMESTAMP DEFAULT NOW() ) `
await sql` CREATE TABLE IF NOT EXISTS dashboard_metrics ( id SERIAL PRIMARY KEY, metric_type VARCHAR(50) NOT NULL, metric_name VARCHAR(100) NOT NULL, metric_value DECIMAL(15, 2) NOT NULL, metadata JSONB, recorded_at TIMESTAMP DEFAULT NOW(), UNIQUE(metric_type, metric_name, recorded_at) ) `
await sql` CREATE TABLE IF NOT EXISTS daily_aggregates ( id SERIAL PRIMARY KEY, date DATE NOT NULL, metric_category VARCHAR(50) NOT NULL, metric_name VARCHAR(100) NOT NULL, total_value DECIMAL(15, 2) NOT NULL, count INTEGER DEFAULT 1, metadata JSONB, created_at TIMESTAMP DEFAULT NOW(), UNIQUE(date, metric_category, metric_name) ) `
console.log('Backend database initialized successfully') } catch (error) { console.error('Failed to initialize backend database:', error) }}12345678910111213141516171819202122232425262728293031323334353637383940414243import { sql } from './db'
export async function isRateLimited(githubId: number, plan: string): Promise<boolean> { const limits: Record<string, number> = { 'free': 10, // 10 PRs per month 'starter': 100, // 100 PRs per month 'pro': 1000, // 1000 PRs per month 'enterprise': 10000 // 10000 PRs per month }
const limit = limits[plan] || limits['free']
try { const firstDayOfMonth = new Date() firstDayOfMonth.setDate(1) firstDayOfMonth.setHours(0, 0, 0, 0)
const result = await sql` SELECT count(*) as count FROM user_events WHERE user_id = ${githubId.toString()} AND event_type = 'api_call' AND created_at >= ${firstDayOfMonth} `
const count = parseInt(result[0].count, 10) return count >= limit } catch (error) { console.error('Rate limit check failed:', error) return false // Fail open to not block users on DB error }}
export async function recordApiCall(githubId: number): Promise<void> { try { await sql` INSERT INTO user_events (event_type, user_id, session_id, metadata) VALUES ('api_call', ${githubId.toString()}, 'backend_session', ${JSON.stringify({ source: 'github_app' })}) ` } catch (error) { console.error('Failed to record API call:', error) }}123456720 unmodified lines28293031323322 unmodified lines5657585960616263646566676817 unmodified lines8687888990919293949596979899100101102103104124 unmodified lines229230231232233234235236237238239240241242243244245246247248import {prixExec} from './utils'import {Project, SyntaxKind} from 'ts-morph'import {readFileSync, existsSync} from 'fs'import {join} from 'path'import pLimit from 'p-limit'import {Bot} from './bot'20 unmodified linesimport {confidenceCalibrator} from './confidence'import {testGenerator} from './test-generator'import {FixVerifier, VerificationResult} from './fix-verifier'let error = console.errorlet info = console.log22 unmodified linesconst commenter: Commenter = new Commenter()const project = new Project()// Initialize shared context engine once at the start using the cloned repo pathtry {const store = als.getStore()const workingDir = store?.workingDir || process.cwd()const repoInfo = store?.repoconst stableId = repoInfo ? `${repoInfo.owner}/${repoInfo.repo}` : undefinedawait unifiedContextEngine.initialize(workingDir, stableId)} catch (e) {info(`Context engine initialization failed: ${e}`)}17 unmodified lines// Skip audit for PRs opened by bots to prevent recursive loops// Also skip if the branch name indicates it's an AI remedy branchconst prAuthor = context.payload.pull_request.user.typeconst branchName = context.payload.pull_request.head.refif (prAuthor === 'Bot' ||branchName.startsWith('ai-remedy/') ||branchName.startsWith('github-actions[bot]')) {info(`Skipping audit: PR author type=${prAuthor}, branch=${branchName}`)return}const inputs: Inputs = new Inputs()inputs.title = context.payload.pull_request.titleif (context.payload.pull_request.body != null) {124 unmodified linesreturn null}try {const store = als.getStore()const workingDir = store?.workingDir || process.cwd()const localPath = join(workingDir, file.filename)if (existsSync(localPath)) {fileContent = readFileSync(localPath, 'utf8')} else {const contents = await octokit.repos.getContent({owner: repo.owner,repo: repo.repo,path: file.filename,ref: context.payload.pull_request.base.sha})if (contents.data != null && !Array.isArray(contents.data)) {if (contents.data.type === 'file' &&contents.data.content != null1234520 unmodified lines262728293031323322 unmodified lines5657585960616263646517 unmodified lines8384858687888990919293949596979899100101102103104105106107108109110111112113114115116124 unmodified lines241242243244245246247248249250251252253254import {prixExec} from './utils'import {Project, SyntaxKind} from 'ts-morph'import pLimit from 'p-limit'import {Bot} from './bot'20 unmodified linesimport {confidenceCalibrator} from './confidence'import {testGenerator} from './test-generator'import {FixVerifier, VerificationResult} from './fix-verifier'import {checkUserPlan} from './user-store'import {isRateLimited, recordApiCall} from './rate-limiter'let error = console.errorlet info = console.log22 unmodified linesconst commenter: Commenter = new Commenter()const project = new Project()// Initialize shared context engine once at the starttry {const workingDir = prixExec('pwd', {encoding: 'utf8'}).trim()await unifiedContextEngine.initialize(workingDir)} catch (e) {info(`Context engine initialization failed: ${e}`)}17 unmodified lines// Skip audit for PRs opened by bots to prevent recursive loops// Also skip if the branch name indicates it's an AI remedy branchconst prAuthorType = context.payload.pull_request.user.typeconst prAuthorId = context.payload.pull_request.user.idconst prAuthorLogin = context.payload.pull_request.user.loginconst branchName = context.payload.pull_request.head.refif (prAuthorType === 'Bot' ||branchName.startsWith('ai-remedy/') ||branchName.startsWith('github-actions[bot]')) {info(`Skipping audit: PR author type=${prAuthorType}, branch=${branchName}`)return}// Check user planconst plan = await checkUserPlan(prAuthorId)// Rate limit checkif (await isRateLimited(prAuthorId, plan)) {info(`Rate limited: User @${prAuthorLogin} on ${plan} plan.`)return}// Record usageawait recordApiCall(prAuthorId)const inputs: Inputs = new Inputs()inputs.title = context.payload.pull_request.titleif (context.payload.pull_request.body != null) {124 unmodified linesreturn null}try {const contents = await octokit.repos.getContent({owner: repo.owner,repo: repo.repo,path: file.filename,ref: context.payload.pull_request.base.sha})if (contents.data != null) {if (!Array.isArray(contents.data)) {if (contents.data.type === 'file' &&contents.data.content != null
src/db.tsAdded+127
src/rate-limiter.tsAdded+43
src/review.ts+31-25