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
14 changes: 14 additions & 0 deletions docs/developer/http-api-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,20 @@ Self-hosted only; requires a **global administrator**.
| `GET` | `/api/admin/backup/info` | `{ attachments_available, attachment_files, attachment_bytes }`: what a backup with files would contain (`attachments_available: false` when attachment storage is not configured). **403** for non-admins, **410** like below. |
| `POST` | `/api/admin/backup` | No body; needs the CSRF header. Query `attachments` (default `true`). Runs `pg_dump --no-owner --no-privileges` against `DATABASE_URL` and returns **200** with `Content-Type: application/gzip` and `Content-Disposition: attachment; filename="marreq-backup_<YYYYMMDD>_<HHMMSS>.tar.gz"`: a tar.gz with `marreq-backup_<…>/database.sql` (plain SQL), `attachments/` (the attachment store, unless `attachments=false` or storage is not configured) and `manifest.json` (`format: "marreq.backup.v1"`, `includes_attachments`, `attachment_files`, `attachment_bytes`). Before issue #341 this was a `.sql.gz`. **403** for non-admins; **410** when the deployment mode disallows backups (`allows_database_backup: false` in `GET /api/meta/deployment`, i.e. cloud); **500** with the `pg_dump` error summary if the dump fails. Success and failure are recorded as `EXPORT` audit rows. The `pg_dump` binary can be overridden with `MARREQ_PG_DUMP`. The Compose nginx allows up to 15 minutes for this route. |

## Admin application cache

Instance-wide (the in-memory cache of the running process); served by both `marreq-server` and `marreq-cloud`. The SPA page is Administration → Cache. Every route except `health` requires a **global administrator**; other authenticated users receive **403**. The `POST` routes take no body and need the CSRF header.

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/cache/stats` | `{ total_entries, active_entries, expired_entries, hits, misses, total_requests, hit_rate, miss_rate, average_access_time_ns, total_access_time_ns, last_cleanup, cache_size_bytes }`. `hit_rate` and `miss_rate` are fractions in 0..1. This is the source the SPA uses. |
| `GET` | `/api/cache/recommendations` | `{ recommendations: string[], priority: "high" \| "medium" \| "low", analysis_timestamp }`. |
| `POST` | `/api/cache/clear` | Drops every entry. Response `{ message, timestamp }`. |
| `POST` | `/api/cache/cleanup` | Drops only the expired entries. Response `{ message, cleaned_entries, timestamp }`. |
| `POST` | `/api/cache/reset-counters` | Zeroes the hit/miss counters; entries are kept. Response `{ message, timestamp }`. |
| `GET` | `/api/cache/performance` | Derived metrics (JSON object). Not used by the SPA: `hit_rate_percentage` is the 0..1 fraction rounded to two decimals, not a percentage, and `memory_usage_mb` is not in megabytes. Use `stats` instead. |
| `GET` | `/api/cache/health` | **Public.** `{ status, total_entries, active_entries, expired_entries, memory_usage, cleanup_needed, last_cleanup }`. `memory_usage` is the entry count, and `last_cleanup` is the time of the request. |

## User management

Instance-wide. All routes require a **global administrator** (`users.is_admin`); other authenticated users receive **403**. Mutating routes need the CSRF header like any other SPA write.
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import AdminPage from '@/pages/AdminPage';
import SystemLogsPage from '@/pages/SystemLogsPage';
import LogAnalyticsPage from '@/pages/LogAnalyticsPage';
import BackupPage from '@/pages/BackupPage';
import CachePage from '@/pages/CachePage';
import CreateRequirementPage from '@/pages/CreateRequirementPage';
import CreateVerificationPage from '@/pages/CreateVerificationPage';
import DashboardPage from '@/pages/DashboardPage';
Expand Down Expand Up @@ -134,6 +135,7 @@ export default function App() {
<Route path="logs" element={<SystemLogsPage />} />
<Route path="logs/analytics" element={<LogAnalyticsPage />} />
<Route path="backup" element={<BackupPage />} />
<Route path="cache" element={<CachePage />} />
</Route>
{/* Project workspace: /:projectSlug/... */}
<Route path=":projectSlug" element={<ProjectLayout />}>
Expand Down
79 changes: 79 additions & 0 deletions frontend/src/api/__tests__/cache.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CSRF, itSendsEachRequest, stubFetch } from '@/test/apiHarness';
import { ApiError } from '../transport';
import {
clearCache,
cleanupCache,
getCacheRecommendations,
getCacheStats,
resetCacheCounters,
} from '../cache';

const stats = {
total_entries: 10,
active_entries: 8,
expired_entries: 2,
hits: 30,
misses: 10,
total_requests: 40,
hit_rate: 0.75,
miss_rate: 0.25,
average_access_time_ns: 1200,
total_access_time_ns: 48000,
last_cleanup: '2026-10-29T08:00:00Z',
cache_size_bytes: 4096,
};

describe('cache API', () => {
afterEach(() => vi.unstubAllGlobals());

itSendsEachRequest([
{
name: 'getCacheStats',
call: () => getCacheStats(),
method: 'GET',
url: '/api/cache/stats',
response: { json: stats },
returns: stats,
},
{
name: 'getCacheRecommendations',
call: () => getCacheRecommendations(),
method: 'GET',
url: '/api/cache/recommendations',
response: {
json: { recommendations: ['Run cleanup'], priority: 'low', analysis_timestamp: '2026-10-29T08:00:00Z' },
},
returns: { recommendations: ['Run cleanup'], priority: 'low', analysis_timestamp: '2026-10-29T08:00:00Z' },
},
{
name: 'clearCache',
call: () => clearCache(CSRF),
method: 'POST',
url: '/api/cache/clear',
response: { json: { message: 'Cache cleared successfully', timestamp: 't' } },
returns: { message: 'Cache cleared successfully', timestamp: 't' },
},
{
name: 'cleanupCache returns the number of removed entries',
call: () => cleanupCache(CSRF),
method: 'POST',
url: '/api/cache/cleanup',
response: { json: { message: 'done', cleaned_entries: 2, timestamp: 't' } },
returns: { message: 'done', cleaned_entries: 2, timestamp: 't' },
},
{
name: 'resetCacheCounters',
call: () => resetCacheCounters(CSRF),
method: 'POST',
url: '/api/cache/reset-counters',
response: { json: { message: 'reset', timestamp: 't' } },
returns: { message: 'reset', timestamp: 't' },
},
]);

it('rejects with an ApiError for non-administrators', async () => {
stubFetch({ status: 403, json: { message: 'forbidden' } });
await expect(getCacheStats()).rejects.toBeInstanceOf(ApiError);
});
});
64 changes: 64 additions & 0 deletions frontend/src/api/cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { fetchJson } from './transport';

/** `GET /api/cache/stats` (site administrators only). Rates are fractions in 0..1. */
export type CacheStats = {
total_entries: number;
active_entries: number;
expired_entries: number;
hits: number;
misses: number;
total_requests: number;
hit_rate: number;
miss_rate: number;
average_access_time_ns: number;
total_access_time_ns: number;
/** RFC 3339 timestamp. */
last_cleanup: string;
cache_size_bytes: number;
};

export type CacheRecommendationPriority = 'high' | 'medium' | 'low';

export type CacheRecommendations = {
recommendations: string[];
priority: CacheRecommendationPriority;
/** RFC 3339 timestamp. */
analysis_timestamp: string;
};

/** Answer of the write endpoints; `cleaned_entries` only comes with a cleanup. */
export type CacheActionResult = {
message: string;
timestamp: string;
cleaned_entries?: number;
};

export async function getCacheStats(): Promise<CacheStats> {
return fetchJson<CacheStats>('/api/cache/stats');
}

export async function getCacheRecommendations(): Promise<CacheRecommendations> {
return fetchJson<CacheRecommendations>('/api/cache/recommendations');
}

function cachePost(path: string, csrfToken: string): Promise<CacheActionResult> {
return fetchJson<CacheActionResult>(path, {
method: 'POST',
headers: { 'X-CSRF-Token': csrfToken },
});
}

/** Drops every cached entry; the next requests rebuild it from the database. */
export function clearCache(csrfToken: string): Promise<CacheActionResult> {
return cachePost('/api/cache/clear', csrfToken);
}

/** Drops only the expired entries. */
export function cleanupCache(csrfToken: string): Promise<CacheActionResult> {
return cachePost('/api/cache/cleanup', csrfToken);
}

/** Zeroes the hit/miss counters without touching the cached entries. */
export function resetCacheCounters(csrfToken: string): Promise<CacheActionResult> {
return cachePost('/api/cache/reset-counters', csrfToken);
}
1 change: 1 addition & 0 deletions frontend/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export * from './meta';
export * from './imports';
export * from './exports';
export * from './logs';
export * from './cache';
export * from './attachments';
export * from './verificationControl';
export * from './reports';
Expand Down
Loading
Loading