Elffuss BraidHub

utopia-ia/elffuss-code public

Test the API providers' fetch signal before the response headers arrive

tests/api-signal.mjs only stopped a call after its first token. There
readSSE's reader.cancel() alone closes the connection, so the check
passed even with no signal on fetch: removing both `signal,` lines from
the fetch options in providers/api.js left all its checks green.

A third case per dialect has the fake server hold its headers and aborts
the call while it waits (the provider still queueing or reading the
prompt). It checks that chat() rejects with an AbortError without
waiting for the answer and that the server sees the request close
before it answers. With fetch given no signal those 4 checks fail; with
the current api.js they pass.
Changesetfe092393385c4ba771d0e641a0a06a87a40a3771ee53d5f7b62875a566ee71a6
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 18:28 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-10 18:28 +02:00
Parentsbd3b0b4729be

Browse the files at this changeset

1 file changed

modified tests/api-signal.mjs +43 −4
@@ -11,7 +11,12 @@
1111 // 1. una llamada normal funciona y trae el texto entero;
1212 // 2. abortar tras el primer token rechaza con AbortError, no entrega ni un
1313 // token más, y el servidor VE cerrarse la conexión antes de terminar
14-// (o sea, que fetch se canceló de verdad y no solo se dejó de leer).
14+// (o sea, que fetch se canceló de verdad y no solo se dejó de leer);
15+// 3. abortar ANTES de que lleguen las cabeceras (el proveedor aún en cola o
16+// leyendo el prompt): rechaza con AbortError en el acto y el servidor ve
17+// cerrarse la petición antes de contestar. Es el caso en que la señal de
18+// fetch importa: en el 2 basta con que readSSE cancele el lector, y ese
19+// caso pasaba igual con fetch sin señal.
1520 //
1621 // BASE=http://localhost:8799 node tests/api-signal.mjs
1722 import http from 'node:http';
@@ -20,15 +25,26 @@
2025 let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
2126
2227 const TOKENS = ['Ho', 'la', ', ', 'soy', ' el', ' proveedor', ' de', ' prueba', '.'];
23-const registro = []; // una entrada por petición: { ruta, enviados, cerradaAntes, terminada }
24-const servidor = http.createServer((req, res) => {
28+const registro = []; // una entrada por petición: { ruta, enviados, cerradaAntes, terminada, contestada }
29+let retrasarCabeceras = false; // el caso 3: el servidor tarda en contestar
30+const servidor = http.createServer(async (req, res) => {
2531 if (req.method === 'OPTIONS') {
2632 res.writeHead(204, { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': '*', 'Access-Control-Allow-Methods': 'POST' });
2733 return res.end();
2834 }
29- const r = { ruta: req.url, enviados: 0, cerradaAntes: false, terminada: false };
35+ const r = { ruta: req.url, enviados: 0, cerradaAntes: false, terminada: false, contestada: false };
3036 registro.push(r);
3137 req.resume();
38+ if (retrasarCabeceras) {
39+ // Sin cabeceras durante un buen rato: si la petición se cierra antes, es
40+ // que fetch la canceló.
41+ const cerrada = await Promise.race([
42+ new Promise(ok => res.on('close', () => ok(true))),
43+ new Promise(ok => setTimeout(() => ok(false), 4000)),
44+ ]);
45+ if (cerrada) { r.cerradaAntes = true; return; }
46+ }
47+ r.contestada = true;
3248 res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Access-Control-Allow-Origin': '*' });
3349 const anthropic = req.url.endsWith('/v1/messages');
3450 let i = 0;
@@ -95,6 +111,29 @@
95111 !!pAbort && pAbort.cerradaAntes && !pAbort.terminada && pAbort.enviados < TOKENS.length,
96112 pAbort ? `enviados ${pAbort.enviados} de ${TOKENS.length}` : 'no llegó la petición');
97113 ok(`${kind} · control: la llamada normal sí llegó al final`, !!pNormal && pNormal.terminada && !pNormal.cerradaAntes);
114+
115+ // 3. Abortar antes de que lleguen las cabeceras.
116+ retrasarCabeceras = true;
117+ const antes3 = registro.length;
118+ const r3 = await p.evaluate(async () => {
119+ const api = await import('/js/providers/api.js');
120+ const ac = new AbortController();
121+ const t0 = performance.now();
122+ let err = null, devuelto;
123+ const prom = api.chat([{ role: 'user', content: 'hola' }], 'sistema', () => {}, ac.signal)
124+ .then(v => { devuelto = v; }, e => { err = { name: e.name }; });
125+ await new Promise(r => setTimeout(r, 500)); // la petición ya salió y espera cabeceras
126+ ac.abort();
127+ await prom;
128+ return { err, devuelto, antesDeContestar: performance.now() - t0 < 3500 };
129+ });
130+ await new Promise(r => setTimeout(r, 300));
131+ retrasarCabeceras = false;
132+ const p3 = registro[antes3];
133+ ok(`${kind} · abortar antes de las cabeceras: rechaza con AbortError sin esperar a que conteste`, r3.err?.name === 'AbortError' && r3.antesDeContestar,
134+ JSON.stringify(r3));
135+ ok(`${kind} · …y el servidor ve cerrarse la petición antes de contestar`, !!p3 && p3.cerradaAntes && !p3.contestada,
136+ p3 ? JSON.stringify(p3) : 'no llegó la petición');
98137 }
99138 ok('ninguna petición intentó salir a una API real', fuera.length === 0, fuera.join(' '));
100139