Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,11 @@ MAX_CONCURRENT_JOBS=2
# token with no extra permissions is enough (public repositories only).
# GITHUB_TOKEN=github_pat_...

# Optional: reuse reports when the same GitHub commit or the same ZIP is
# analyzed again (in memory; cleared on restart). 0 entries = no caching.
REPORT_CACHE_MAX_ENTRIES=50
REPORT_CACHE_TTL_HOURS=168

# Optional: rate limits on starting analyses (0 = no limit)
RATE_LIMIT_PER_HOUR=5 # per visitor (IP address)
RATE_LIMIT_PER_DAY=100 # whole site
Expand All @@ -351,13 +356,21 @@ SAVE_DEBUG_ARTIFACTS=false

| Method | Path | Description |
|---|---|---|
| `POST` | `/api/analyze` | Upload a ZIP (`repository` form field). Returns `202 { jobId }`. |
| `POST` | `/api/analyze/github` | JSON `{ "url": "https://github.com/owner/repo" }`. Public repositories only; checked on GitHub before the job starts. Returns `202 { jobId, repository }`. |
| `POST` | `/api/analyze` | Upload a ZIP (`repository` form field; optional `force=true`). |
| `POST` | `/api/analyze/github` | JSON `{ "url": "https://github.com/owner/repo", "force"?: true }`. Public repositories only; checked on GitHub before the job starts. |
| `GET` | `/api/jobs/:id/events` | Server-Sent Events: `progress`, then `completed` (report + markdown) or `failed` (error body). |
| `GET` | `/api/jobs/:id` | Current job state as JSON. |
| `GET` | `/api/health` | Health check. |

Starting an analysis is rate limited per visitor and per day for the whole site (HTTP 429 with a message saying when to retry). Only accepted analyses count, and limits are checked before the upload is received.
Both analyze endpoints return a `jobId` to follow:

- `202` a new analysis started
- `200 { cached: true }` the same GitHub commit or the same ZIP (by SHA-256) was analyzed before, so the stored report is returned instantly
- `200 { joined: true }` the same input is already being analyzed, so the request shares that job

Cached reports are keyed by an analysis version (model, settings, prompt and schema), so changing any of those stops old reports from being reused. `force` skips the cache.

Starting an analysis is rate limited per visitor and per day for the whole site (HTTP 429 with a message saying when to retry). Only new analyses (`202`) count, not cached or joined results, and limits are checked before the upload is received.

Each analysis runs as its own job, so concurrent users never see each other's progress. Finished jobs are kept in memory for 30 minutes.

Expand Down
5 changes: 5 additions & 0 deletions apps/backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ MAX_CONCURRENT_JOBS=2
# A fine-grained token with no extra permissions is enough (public repos only).
# GITHUB_TOKEN=

# Reuse reports when the same GitHub commit or ZIP is analyzed again
# (in memory; cleared on restart). 0 entries = no caching.
REPORT_CACHE_MAX_ENTRIES=50
REPORT_CACHE_TTL_HOURS=168

# Rate limits on starting analyses (0 = no limit).
# Per visitor (IP address) per hour, and for the whole site per day.
RATE_LIMIT_PER_HOUR=5
Expand Down
23 changes: 21 additions & 2 deletions apps/backend/src/application/analysis-job.runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { JobLogger } from "../logger/logger.service.js";
import { toErrorResponse } from "../http/error-response.js";
import { downloadRepositoryZip } from "../github/github.client.js";
import { MAX_UPLOAD_SIZE } from "../constants/upload.js";
import { reportCache } from "../cache/report-cache.js";

import type { AnalysisSource, JobContext } from "../jobs/job.types.js";
import type { RepositoryInfo } from "../types/repository-info.js";
Expand Down Expand Up @@ -62,13 +63,19 @@ async function prepareSource(
};
}

export interface RunOptions {
/** Store the result under this key for reuse. */
cacheKey?: string;
}

/**
* Runs one analysis job in the background and records the outcome
* in the job store. Never throws: every failure becomes a failed job.
*/
export async function runAnalysisJob(
jobId: string,
source: AnalysisSource,
options: RunOptions = {},
): Promise<void> {
const logger = new JobLogger(jobId);

Expand All @@ -86,16 +93,28 @@ export async function runAnalysisJob(
// Deletes the ZIP and extracted files when done.
const result = await analyzeUploadedRepository(zipPath, context, repository);

jobStore.complete(jobId, {
const jobResult = {
report: result.report,
markdown: result.markdown,
repository,
});
analyzedAt: new Date().toISOString(),
cached: false,
};

if (options.cacheKey) {
await reportCache.save(options.cacheKey, jobResult);
}

jobStore.complete(jobId, jobResult);

await logger.info("Repository analysis completed", result.trace);
} catch (error) {
await logger.error("Repository analysis failed", error);

jobStore.fail(jobId, toErrorResponse(error));
} finally {
if (options.cacheKey) {
reportCache.release(options.cacheKey, jobId);
}
}
}
35 changes: 35 additions & 0 deletions apps/backend/src/cache/analysis-version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { createHash } from "node:crypto";

import { env } from "../config/env.js";
import {
ANALYSIS_TASK,
REPORT_REQUIREMENTS,
SYSTEM_INSTRUCTION,
} from "../ai/prompt/prompt.constants.js";
import { ENGINEERING_REPORT_JSON_SCHEMA } from "../ai/report/report.json-schema.js";

/**
* Bump when the pipeline changes in a way the fingerprint below cannot
* see (e.g. how files are ranked, filtered or formatted in the prompt),
* so cached reports from the old pipeline are no longer reused.
*/
const PIPELINE_REVISION = 1;

/**
* Fingerprint of everything that shapes a report: model, settings,
* prompt text, output schema and pipeline revision. Part of every cache
* key, so changing any of them makes old cached reports stop matching.
*/
export const ANALYSIS_VERSION = createHash("sha256")
.update(
JSON.stringify({
revision: PIPELINE_REVISION,
model: env.GEMINI_MODEL,
temperature: env.GEMINI_TEMPERATURE ?? null,
maxPromptTokens: env.MAX_PROMPT_TOKENS,
prompt: [SYSTEM_INSTRUCTION, ANALYSIS_TASK, REPORT_REQUIREMENTS],
schema: ENGINEERING_REPORT_JSON_SCHEMA,
}),
)
.digest("hex")
.slice(0, 12);
78 changes: 78 additions & 0 deletions apps/backend/src/cache/report-cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import fs from "node:fs";
import { createHash } from "node:crypto";
import { pipeline } from "node:stream/promises";

import { env } from "../config/env.js";
import { jobStore } from "../jobs/job.store.js";
import type { JobResult } from "../jobs/job.types.js";
import { ANALYSIS_VERSION } from "./analysis-version.js";
import { MemoryReportStore, type ReportStore } from "./report-store.js";

/**
* Cache key for a GitHub commit. The repository name is included so a
* fork with the same commit still gets a report labelled with its name.
*/
export function githubCacheKey(fullName: string, commitSha: string): string {
return `${ANALYSIS_VERSION}:github:${fullName.toLowerCase()}@${commitSha}`;
}

/**
* Cache key for an uploaded ZIP: the SHA-256 of its bytes, so the same
* archive uploaded again (by anyone) reuses the report.
*/
export async function uploadCacheKey(zipPath: string): Promise<string> {
const hash = createHash("sha256");

await pipeline(fs.createReadStream(zipPath), hash);

return `${ANALYSIS_VERSION}:zip:${hash.digest("hex")}`;
}

/**
* Reuses finished reports and joins identical analyses already running.
*/
export class ReportCache {
private readonly inFlight = new Map<string, string>();

constructor(private readonly store: ReportStore) {}

async lookup(key: string): Promise<JobResult | undefined> {
return this.store.get(key);
}

async save(key: string, result: JobResult): Promise<void> {
await this.store.set(key, result);
}

/**
* Id of a job already analyzing this input, if one is still running.
*/
runningJob(key: string): string | undefined {
const jobId = this.inFlight.get(key);

if (jobId && jobStore.get(jobId)?.status === "running") {
return jobId;
}

this.inFlight.delete(key);

return undefined;
}

track(key: string, jobId: string): void {
this.inFlight.set(key, jobId);
}

release(key: string, jobId: string): void {
if (this.inFlight.get(key) === jobId) {
this.inFlight.delete(key);
}
}
}

export const reportCache = new ReportCache(
new MemoryReportStore(
env.REPORT_CACHE_MAX_ENTRIES,
env.REPORT_CACHE_TTL_HOURS * 60 * 60 * 1000,
),
);
68 changes: 68 additions & 0 deletions apps/backend/src/cache/report-store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import type { JobResult } from "../jobs/job.types.js";

/**
* Where finished reports are kept for reuse. The in-memory store below
* is the default; a database-backed store can implement the same
* interface later (e.g. for saved, shareable reports).
*/
export interface ReportStore {
get(key: string): Promise<JobResult | undefined>;
set(key: string, result: JobResult): Promise<void>;
}

interface Entry {
result: JobResult;
expiresAt: number;
}

/**
* Least-recently-used cache in process memory, with a time limit per
* entry. Cleared when the server restarts (or sleeps on Render's free
* plan).
*/
export class MemoryReportStore implements ReportStore {
private readonly entries = new Map<string, Entry>();

constructor(
private readonly maxEntries: number,
private readonly ttlMs: number,
private readonly now: () => number = Date.now,
) {}

async get(key: string): Promise<JobResult | undefined> {
const entry = this.entries.get(key);

if (!entry) {
return undefined;
}

if (entry.expiresAt <= this.now()) {
this.entries.delete(key);
return undefined;
}

// Map keeps insertion order: re-insert to mark as recently used.
this.entries.delete(key);
this.entries.set(key, entry);

return entry.result;
}

async set(key: string, result: JobResult): Promise<void> {
if (this.maxEntries <= 0) {
return;
}

this.entries.delete(key);
this.entries.set(key, { result, expiresAt: this.now() + this.ttlMs });

while (this.entries.size > this.maxEntries) {
const oldest = this.entries.keys().next().value as string;
this.entries.delete(oldest);
}
}

get size(): number {
return this.entries.size;
}
}
9 changes: 9 additions & 0 deletions apps/backend/src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@ const envSchema = z.object({
.string()
.optional()
.transform((value) => value?.trim() || undefined),
/**
* Finished reports kept in memory for reuse when the same GitHub
* commit or the same ZIP is analyzed again. 0 = no caching.
*/
REPORT_CACHE_MAX_ENTRIES: z.coerce.number().int().min(0).default(50),
/**
* How long a cached report is reused, in hours.
*/
REPORT_CACHE_TTL_HOURS: z.coerce.number().positive().default(168),
/**
* Upper bound on the prompt size sent to Gemini. Source files are
* ranked by importance and added until this budget is reached.
Expand Down
7 changes: 5 additions & 2 deletions apps/backend/src/http/rate-limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@ const passThrough: RequestHandler = (_req, _res, next) => next();
* rotate through addresses)
* - whole site: RATE_LIMIT_PER_DAY analyses per day across all visitors
*
* Only accepted analyses count: requests that end in an error
* (bad upload, server busy, limit reached) do not use up the limit.
* Only analyses that actually start (HTTP 202) count: errors (bad
* upload, server busy, limit reached) and reused results (a cached
* report, or joining an identical analysis already running) do not.
* Runs before the upload is received, so a limited visitor cannot
* send a large file first.
*
Expand All @@ -51,6 +52,7 @@ export const analysisRateLimits: RequestHandler[] = [
limit: env.RATE_LIMIT_PER_DAY,
keyGenerator: () => "site",
skipFailedRequests: true,
requestWasSuccessful: (_req, res) => res.statusCode === 202,
standardHeaders: "draft-8",
legacyHeaders: false,
handler: (req, res) => {
Expand All @@ -71,6 +73,7 @@ export const analysisRateLimits: RequestHandler[] = [
limit: env.RATE_LIMIT_PER_HOUR,
keyGenerator: (req) => ipKeyGenerator(req.ip ?? "unknown"),
skipFailedRequests: true,
requestWasSuccessful: (_req, res) => res.statusCode === 202,
standardHeaders: "draft-8",
legacyHeaders: false,
handler: (req, res) => {
Expand Down
4 changes: 4 additions & 0 deletions apps/backend/src/jobs/job.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ export interface JobResult {
report: EngineeringReport;
markdown: string;
repository: RepositoryInfo;
/** When the analysis ran (ISO 8601). Older than now for cached results. */
analyzedAt: string;
/** True when this result was reused from the cache. */
cached: boolean;
}

/**
Expand Down
Loading
Loading