From 31e9619727954c93c540d00738533274a5b237cd Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Mon, 5 Oct 2026 20:40:12 +0200 Subject: [PATCH] feat(backend): stream /api/chat as spec-compliant SSE Expose the bare `data:`/`[DONE]` contract on the main chat endpoint so simple clients can consume the stream without parsing named events. --- backend/README.md | 66 ++++++++++++++++++++--- backend/src/routes/chat.js | 45 ++++++++++------ backend/src/services/chat-stream.js | 83 +++++++++++++++++++++++++++++ backend/test/helpers.js | 30 +++++++++++ backend/test/stream.test.js | 67 ++++++++++++++++++++++- 5 files changed, 269 insertions(+), 22 deletions(-) diff --git a/backend/README.md b/backend/README.md index 1ea488a..48ffac2 100644 --- a/backend/README.md +++ b/backend/README.md @@ -27,7 +27,7 @@ un modèle déjà téléchargé (`ollama pull llama3.2`). | PATCH | `/api/auth/me` | oui | Met à jour le profil (nom) | | POST | `/api/auth/password` | oui | Change le mot de passe | | POST | `/api/auth/logout` | oui | Déconnexion (204) | -| POST | `/api/chat` | oui | Envoie un prompt à Jarvis via Ollama | +| POST | `/api/chat` | oui | Chat streamé en SSE (contrat minimal, `data:`) | | GET | `/api/chat/models` | oui | Modèles Ollama disponibles | | POST | `/api/projects` | oui | Crée un projet | | GET | `/api/projects` | oui | Liste les projets de l'utilisateur | @@ -74,11 +74,65 @@ curl -X POST http://localhost:3000/api/auth/register \ -H 'Content-Type: application/json' \ -d '{"email":"tony@stark.com","password":"motdepasse123","name":"Tony"}' -# Chat (remplacer ) -curl -X POST http://localhost:3000/api/chat \ +# Chat streamé (remplacer ) : -N désactive la mise en tampon de curl +curl -N -X POST http://localhost:3000/api/chat \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ - -d '{"message":"Quel temps fait-il ?"}' + -d '{"model":"llama3.2","messages":[{"role":"user","content":"Quel temps fait-il ?"}]}' +``` + +### Streaming minimal : `POST /api/chat` + +Ce endpoint suit le contrat SSE le plus simple, sans évènements nommés : chaque morceau +de texte arrive dans une ligne `data: {"content":"…"}` et le flux se termine par +`data: [DONE]`. Un échec survenu **après** l'ouverture du flux est signalé par +`data: {"error":"…"}` ; si Ollama est injoignable avant, la réponse est une erreur HTTP +classique (JSON). + +Body attendu : + +```json +{ + "model": "llama3.2", + "messages": [ + { "role": "user", "content": "Salut Jarvis" } + ] +} +``` + +`messages` doit être un tableau non vide (`role` ∈ `system` `user` `assistant`). + +Exemple client (JavaScript vanilla / `fetch`) : + +```js +const res = await fetch('http://localhost:3000/api/chat', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }, + body: JSON.stringify({ + model: 'llama3.2', + messages: [{ role: 'user', content: 'Salut Jarvis' }], + }), +}); + +const reader = res.body.getReader(); +const decoder = new TextDecoder(); +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); + const data = block.match(/^data: (.+)$/m)?.[1]; + if (!data) continue; // ignore les commentaires de keep-alive + if (data === '[DONE]') return; + process.stdout.write(JSON.parse(data).content); + } +} ``` ### Streaming (SSE) @@ -141,8 +195,8 @@ d'authentification (20 req/min). npm test ``` -Suite `node:test` (25 tests) couvrant l'authentification, l'isolation des projets, la pagination -du contexte et le streaming SSE. Ollama est remplacé par un mock : aucun service externe requis. +Suite `node:test` (29 tests) couvrant l'authentification, l'isolation des projets, la pagination +du contexte et le streaming SSE (contrat minimal + évènements nommés). Ollama est remplacé par un mock : aucun service externe requis. ## Docker diff --git a/backend/src/routes/chat.js b/backend/src/routes/chat.js index bda83bd..bfab676 100644 --- a/backend/src/routes/chat.js +++ b/backend/src/routes/chat.js @@ -1,5 +1,28 @@ -import { streamChatToClient } from '../services/chat-stream.js'; -import { OllamaError } from '../lib/errors.js'; +import { streamChatToClient, streamChatToClientSpec } from '../services/chat-stream.js'; + +// Contract of `POST /api/chat`: a non-empty `messages` array, optionally a model. +const specChatSchema = { + type: 'object', + required: ['messages'], + additionalProperties: false, + properties: { + model: { type: 'string', maxLength: 120 }, + messages: { + type: 'array', + minItems: 1, + maxItems: 50, + items: { + type: 'object', + required: ['role', 'content'], + additionalProperties: false, + properties: { + role: { type: 'string', enum: ['system', 'user', 'assistant'] }, + content: { type: 'string', minLength: 1, maxLength: 32000 }, + }, + }, + }, + }, +}; const chatSchema = { type: 'object', @@ -30,22 +53,14 @@ const chatSchema = { * @param {import('fastify').FastifyInstance} fastify */ export async function chatRoutes(fastify) { + // Spec-compliant endpoint: streams the answer over SSE as bare `data:` + // messages, terminated by `data: [DONE]`. fastify.post( '/api/chat', - { onRequest: [fastify.authenticate], schema: { body: chatSchema } }, + { onRequest: [fastify.authenticate], schema: { body: specChatSchema } }, async (request, reply) => { - const { message, model, history = [] } = request.body; - const messages = [...history, { role: 'user', content: message }]; - - try { - const result = await fastify.ollama.chat({ messages, model }); - return reply.send({ reply: result.reply, model: result.model, user: { id: request.user.sub } }); - } catch (error) { - if (error instanceof OllamaError) { - return reply.code(error.status).send({ error: error.message }); - } - throw error; - } + const { model, messages } = request.body; + return streamChatToClientSpec({ ollama: fastify.ollama, reply, request, messages, model }); }, ); diff --git a/backend/src/services/chat-stream.js b/backend/src/services/chat-stream.js index 2b5b10a..3e0f40f 100644 --- a/backend/src/services/chat-stream.js +++ b/backend/src/services/chat-stream.js @@ -88,3 +88,86 @@ export async function streamChatToClient({ ollama, reply, request, messages, mod if (!raw.writableEnded) raw.end(); } } + +/** + * Streams a stateless answer using the minimal, `data:`-only SSE contract of + * `POST /api/chat`: + * + * data: {"content":"text chunk"} + * data: {"content":"..."} + * data: [DONE] + * + * A failure that happens once the stream is open is reported inline as + * `data: {"error":"..."}`, while an unreachable Ollama is still answered with a + * real HTTP status before any SSE byte is sent. Aborts the Ollama request if the + * client disconnects mid-generation. + * + * @param {object} options + * @param {{ openChatStream: Function, readStream: Function }} options.ollama + * @param {import('fastify').FastifyReply} options.reply + * @param {import('fastify').FastifyRequest} options.request + * @param {Array<{role: string, content: string}>} options.messages + * @param {string} [options.model] + */ +export async function streamChatToClientSpec({ ollama, reply, request, messages, model }) { + const controller = new AbortController(); + + // Open the Ollama stream before switching to SSE: if Ollama is unreachable we + // can still answer with a real HTTP error code instead of a broken stream. + let opened; + try { + opened = await ollama.openChatStream({ messages, model, signal: controller.signal }); + } catch (error) { + const status = error instanceof OllamaError ? error.status : 500; + const message = error instanceof Error ? error.message : 'Internal server error.'; + return reply.code(status).send({ error: message }); + } + + const raw = reply.raw; + reply.hijack(); + + raw.writeHead(200, { + 'Content-Type': 'text/event-stream; charset=utf-8', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive', + 'X-Accel-Buffering': 'no', // disable buffering on reverse proxies (nginx) + }); + + // Only a close before we finish means the client went away; a close triggered + // by our own raw.end() must not abort anything. + const onClientClose = () => { + if (!raw.writableEnded) controller.abort(); + }; + raw.on('close', onClientClose); + + const sendData = (payload) => { + if (raw.writableEnded) return false; + const text = typeof payload === 'string' ? payload : JSON.stringify(payload); + return raw.write(`data: ${text}\n\n`); + }; + + // Opening comment: the client receives the headers immediately. + raw.write(': stream open\n\n'); + + try { + for await (const chunk of ollama.readStream(opened.response)) { + if (raw.writableEnded || controller.signal.aborted) break; + + const delta = chunk?.message?.content ?? ''; + if (delta) sendData({ content: delta }); + + if (chunk?.done) break; + } + + if (controller.signal.aborted || raw.writableEnded) return; + sendData('[DONE]'); + } catch (error) { + if (!controller.signal.aborted) { + request.log.error(error); + sendData({ error: error instanceof Error ? error.message : 'Error while streaming.' }); + } + } finally { + raw.off('close', onClientClose); + if (!raw.writableEnded) raw.end(); + } +} diff --git a/backend/test/helpers.js b/backend/test/helpers.js index f937f10..9457d4b 100644 --- a/backend/test/helpers.js +++ b/backend/test/helpers.js @@ -73,6 +73,36 @@ export async function registerUser(base, email = `u${Date.now()}${Math.random()} 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. */ diff --git a/backend/test/stream.test.js b/backend/test/stream.test.js index 5a1a033..6fe6701 100644 --- a/backend/test/stream.test.js +++ b/backend/test/stream.test.js @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import { after, before, describe, it } from 'node:test'; -import { api, readSse, registerUser, startServer } from './helpers.js'; +import { api, readSse, readSsePayloads, registerUser, startServer } from './helpers.js'; const FULL_REPLY = 'Bonjour Tony, je suis Jarvis.'; @@ -111,3 +111,68 @@ describe('streaming over SSE', () => { assert.equal(deltas.join(''), FULL_REPLY); }); }); + +describe('POST /api/chat (spec SSE contract)', () => { + let srv; + let user; + + before(async () => { + srv = await startServer(); + user = await registerUser(srv.base, 'chat@x.io'); + }); + + after(async () => { + await srv.close(); + }); + + function postChat(body, token = user.token) { + return fetch(`${srv.base}/api/chat`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + body: JSON.stringify(body), + }); + } + + it('requires authentication', async () => { + assert.equal((await postChat({ messages: [{ role: 'user', content: 'Hi' }] }, null)).status, 401); + }); + + it('rejects a missing or empty messages array', async () => { + assert.equal((await postChat({})).status, 400); + assert.equal((await postChat({ messages: [] })).status, 400); + assert.equal((await postChat({ messages: [{ role: 'user' }] })).status, 400); + }); + + it('streams `data: {"content":...}` chunks then `data: [DONE]`', async () => { + const res = await postChat({ + model: 'mock:1', + messages: [{ role: 'user', content: 'Hello' }], + }); + + assert.equal(res.status, 200); + assert.match(res.headers.get('content-type') ?? '', /text\/event-stream/); + assert.match(res.headers.get('cache-control') ?? '', /no-cache/); + assert.match(res.headers.get('connection') ?? '', /keep-alive/); + + const payloads = await readSsePayloads(res); + assert.equal(payloads.at(-1), '[DONE]'); + + const content = payloads + .slice(0, -1) + .map((p) => JSON.parse(p).content) + .join(''); + assert.equal(content, FULL_REPLY); + assert.ok(payloads.length - 1 >= 5, `chunks received: ${payloads.length - 1}`); + }); + + it('answers with a real HTTP error when Ollama fails before the stream', async () => { + const res = await postChat({ model: 'boom', messages: [{ role: 'user', content: 'boom' }] }); + + assert.ok(res.status >= 400, `status: ${res.status}`); + assert.match(res.headers.get('content-type') ?? '', /application\/json/); + assert.ok((await res.json()).error); + }); +});