Files
Jarvise-project/backend/test/helpers.js
T
BlackAngelTV 6ebf550eb0 feat(backend): bound the messages kept per project
A project that lives for months would otherwise grow the SQLite file without
limit, even though the model only ever reads the most recent messages. Pruning
the oldest rows on every write keeps a project to a fixed budget without
touching what the context is built from.
2026-10-05 21:39:45 +02:00

141 lines
4.0 KiB
JavaScript

import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { buildApp } from '../src/app.js';
import { loadConfig } from '../src/config.js';
import { createDatabase } from '../src/db/index.js';
import { createOllama } from '../src/services/ollama.js';
import { startMockOllama } from './mock-ollama.js';
/** Starts an isolated instance (in-memory database + mock Ollama) on a free port. */
export async function startServer(options = {}) {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'jarvise-test-'));
const mock = await startMockOllama(options);
const config = loadConfig({
env: 'test',
jwtSecret: 'test-secret',
dbPath: ':memory:',
ollamaUrl: mock.url,
ollamaModel: 'mock:1',
maxMessagesPerProject: options.maxMessagesPerProject,
});
const db = createDatabase(config.dbPath, {
maxMessagesPerProject: config.messages.maxPerProject,
});
const ollama = createOllama(config);
const app = await buildApp({ config, db, ollama });
await app.listen({ port: 0, host: '127.0.0.1' });
const { port } = app.server.address();
return {
app,
db,
mock,
base: `http://127.0.0.1:${port}`,
async close() {
await app.close();
await mock.close();
fs.rmSync(tmpDir, { recursive: true, force: true });
},
};
}
/** Simple JSON request; only sets Content-Type when there is a body. */
export async function api(base, method, apiPath, { token, body, headers = {} } = {}) {
const res = await fetch(base + apiPath, {
method,
headers: {
...(body ? { 'Content-Type': 'application/json' } : {}),
...(token ? { Authorization: `Bearer ${token}` } : {}),
...headers,
},
body: body ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let json = null;
try {
json = text ? JSON.parse(text) : null;
} catch {
json = text;
}
return { status: res.status, json, headers: res.headers };
}
/** Creates a user and returns its token. */
export async function registerUser(base, email = `u${Date.now()}${Math.random()}@x.io`) {
const res = await api(base, 'POST', '/api/auth/register', {
body: { email, password: 'motdepasse123', name: 'Test' },
});
if (res.status !== 201) throw new Error(`register failed: ${JSON.stringify(res.json)}`);
return { token: res.json.token, user: res.json.user, email };
}
/**
* Consumes an SSE stream and returns each `data:` line verbatim (no JSON parse),
* which is what the `[DONE]` sentinel requires.
*/
export async function readSsePayloads(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
const payloads = [];
let buffer = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let sep;
while ((sep = buffer.indexOf('\n\n')) !== -1) {
const block = buffer.slice(0, sep);
buffer = buffer.slice(sep + 2);
if (!block || block.startsWith(':')) continue;
for (const line of block.split('\n')) {
if (line.startsWith('data: ')) payloads.push(line.slice(6));
}
}
}
return payloads;
}
/**
* Consumes an SSE stream and returns the events as `{ event, data }` objects.
*/
export async function readSse(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
const events = [];
let buffer = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let sep;
while ((sep = buffer.indexOf('\n\n')) !== -1) {
const block = buffer.slice(0, sep);
buffer = buffer.slice(sep + 2);
if (!block || block.startsWith(':')) continue;
let event = 'message';
let data = '';
for (const line of block.split('\n')) {
if (line.startsWith('event: ')) event = line.slice(7).trim();
else if (line.startsWith('data: ')) data += line.slice(6);
}
events.push({ event, data: data ? JSON.parse(data) : null });
}
}
return events;
}