Promise vere e await: la coda dei microtask viene svuotata

Il difetto: Boa le Promise le ha, ma nessuno chiamava run_jobs(), quindi ogni
.then restava in coda per sempre e la pagina non si aggiornava — senza un solo
errore da leggere.

- fetch restituisce una Promise costruita dal motore (new Promise + resolve/reject
  tenuti nella richiesta), non più un oggetto con un then finto
- text() e json() restituiscono Promise anche loro, come nel browser: senza,
  "await r.text()" riceveva la stringa e chi si aspettava una Promise si rompeva
- run_jobs() dopo ogni ingresso di JavaScript: script, eventi, timer, consegna
  delle risposte di fetch
- il guscio desktop serve le fetch anche nel percorso senza finestra: con
  --aspetta l'attesa non serviva a niente e la pagina restava sulla scritta iniziale
- 7 test nuovi (tests/promise.rs): then, await, fetch+text, fetch+json, catch,
  Promise.all, Promise accesa dentro un gestore di clic
- aggiornato il test che si aspettava r.text() sincrona: codificava la vecchia
  semplificazione, non il comportamento giusto

Verifica end-to-end su HTTP vero: una pagina con await fetch e await r.json()
mostra "ricevuto: Mosaic (200)". Wikipedia, che usa async/await ovunque, si carica
senza panic.
This commit is contained in:
Carlo Baratto committed 2026-11-13 09:01:35 +01:00
1 parent 71f45d8967
commit 6a14853d0d
6 files changed
+241 -18

No files matched your search

+8
View File
@@ -510,7 +510,15 @@ fn main() {
let fine = adesso_ms() + aspetta;
while adesso_ms() < fine {
std::thread::sleep(std::time::Duration::from_millis(10));
// `--aspetta` serve proprio a dare tempo alla rete: senza
// servire le fetch qui, l'attesa non faceva nulla e la
// pagina restava sulla scritta iniziale
let mut cambiato =
servi_fetch(&mut macchina, &mut contenuto, &client, page.base_url.as_deref());
if pompa_timer(&mut macchina, &mut contenuto, Some(&r), &mut form) {
cambiato = true;
}
if cambiato {
if let Ok(nuovo) =
render_page(&page, &contenuto, size.0, size.1, zoom as f32, &font, &form)
{
+1 -1
View File
@@ -66,7 +66,7 @@ gusci (Sailfish e desktop) ricostruiti sullo stesso motore.
| M2.2 Flexbox | `display:flex`, direzione, `justify-content`, `align-items`, `gap`, `flex-basis/grow/shrink`, wrap | **fatto** (casi 68–73) |
| M2.3 Tabelle | modello tabella, `colspan`, larghezze automatiche e dichiarate | **fatto** (casi 74–76); `rowspan` e `border-collapse` restano fuori |
| M2.4 Formulari | input testo/password, checkbox, radio, select, textarea, pulsanti, fuoco, tastiera virtuale | **fatto** (casi 77–80); mancano invio del form, caret/selezione, menu a comparsa |
| M2.5 Scripting | motore JS `Boa`, binding DOM, event loop | **fatto** per il perimetro dichiarato: script inline ed esterni nell'ordine del documento, `getElementById`/`querySelector`/`querySelectorAll`, testo, attributi, `dataset`, `style`, `classList`, navigazione, costruzione di nodi, `innerHTML` e `insertAdjacentHTML`, eventi `click`/`input`/`submit`/`keydown`/`focus`/`blur`/`change` con propagazione, `stopPropagation`, `preventDefault`, handler inline, `element.value`, `console.log`, timer con orologio iniettato, `fetch` con risposta consegnata dal guscio. **Fuori ambito dichiarato:** Promise vere (il `then` di `fetch` è una catena semplificata, `await` non funziona), cattura degli eventi, pseudo-classi nei selettori, `closest`, Canvas/SVG |
| M2.5 Scripting | motore JS `Boa`, binding DOM, event loop | **fatto** per il perimetro dichiarato: script inline ed esterni nell'ordine del documento, `getElementById`/`querySelector`/`querySelectorAll`, testo, attributi, `dataset`, `style`, `classList`, navigazione, costruzione di nodi, `innerHTML` e `insertAdjacentHTML`, eventi `click`/`input`/`submit`/`keydown`/`focus`/`blur`/`change` con propagazione, `stopPropagation`, `preventDefault`, handler inline, `element.value`, `console.log`, timer con orologio iniettato, `fetch` con risposta consegnata dal guscio. **Promise vere e `await`** (chiuso dopo M2.6): `fetch` restituisce una Promise del motore, `text()`/`json()` anche, e la coda dei microtask (`run_jobs`) viene svuotata dopo ogni ingresso di JavaScript — script, eventi, timer, consegna delle risposte. **Fuori ambito dichiarato:** cattura degli eventi, pseudo-classi nei selettori, `closest`, Canvas/SVG |
| M2.6 Rete | HTTP/1.1, `fetch`, cache, cookie, processo di rete separato | **fatto** per il perimetro dichiarato: `GET`/`POST` http e https con TLS, `Content-Length`/chunked, reindirizzamenti, limiti, sotto-risorse (CSS, immagini, script) con URL risolti sul documento, invio dei formulari, `Client` con **cookie** (`Set-Cookie`, `Domain`, `Path`, `Secure`, `Max-Age`, `Expires`) e **cache** con scadenza, usato da navigazione, invio, `fetch` e sotto-risorse. **Aggiunte in M2.6b:** **HTTP/2** (preface, `SETTINGS`, `HEADERS`/`CONTINUATION`, `DATA`, `WINDOW_UPDATE`, `PING`, `RST_STREAM`, `GOAWAY`; HPACK con tabella statica, dinamica e Huffman — tabelle generate dalla RFC 7541 e validate sui suoi esempi); **proxy** `http_proxy`/`https_proxy`/`all_proxy`/`no_proxy` con tunnel `CONNECT` e `Proxy-Authorization`; **`multipart/form-data`** e `text/plain` oltre al `urlencoded`; **processo di rete separato** (`mosaic-net`: IPC a lunghezza prefissata su stdin/stdout, cookie e cache nel servizio) usato dal desktop con `--rete-esterna`.
**Fuori ambito dichiarato:** multiplexing HTTP/2, `PUSH_PROMISE` e priorità; proxy SOCKS e PAC; invio di file (`input type=file`); sul telefono il servizio di rete resta nel processo, perché un'app sandboxata non avvia processi figli in modo affidabile. **Sul telefono** `fetch` e i cookie sono collegati: sessione di rete nel confine C (`engine_session_*`), documento creato con la sessione, richieste degli script eseguite dal guscio e consegnate al motore |
| M2.7 Compositor | tile, danni, scroll compositato, animazioni (`wgpu`) | da fare |
+1
View File
@@ -54,6 +54,7 @@ Nessun codice di WebKit, Blink, Gecko o Servo: parser, cascata, layout e raster
| Proxy `http_proxy`/`https_proxy`/`no_proxy`, tunnel `CONNECT` | fatto (M2.6b) | `src/net.rs` |
| `multipart/form-data` e `text/plain` oltre a `urlencoded` | fatto (M2.6b) | `src/invio.rs` |
| Processo di rete separato con IPC su stdin/stdout | fatto (M2.6b, desktop) | `src/bin/mosaic-net.rs` |
| Promise vere e `await`, `fetch` come Promise, `run_jobs` sui microtask | fatto (M2.5 chiuso) | `src/script_boa.rs` |
| Rete: `GET` http/https con TLS, chunked, reindirizzamenti, limiti | fatto in parte (M2.6) | `src/net.rs`, `render --url`, `desktop --url` |
| Sotto-risorse dalla rete: `link[rel=stylesheet]` e `img[src]` | fatto (M2.6) | `src/resource.rs`, `tests/risorse.rs` |
| WPT (`html/syntax/parsing` ≥ 90 %) | mancante | — |
+33 -16
View File
@@ -172,8 +172,11 @@ function __timer_prossimo() {
}
/* fetch: la richiesta si accoda, la esegue il guscio (che sa fare rete) e la
risposta torna qui con __risposta(). Il corpo si legge in modo sincrono
(`r.text()`), semplificazione dichiarata rispetto alle Promise. */
risposta torna qui con __risposta(). È una Promise vera, costruita dal
costruttore del motore: `then`, `catch`, `await` e `Promise.all` funzionano,
purché la coda dei microtask venga svuotata dopo ogni evento — lo fa la parte
Rust con `run_jobs`. `text()` e `json()` restituiscono Promise anche loro, come
nel browser: senza, `await r.text()` darebbe la stringa e non una Promise. */
var __richieste = [];
var __prossima_richiesta = 1;
@@ -184,16 +187,13 @@ function fetch(url, opzioni) {
id: id,
url: String(url),
metodo: opz.method ? String(opz.method).toUpperCase() : 'GET',
corpo: (opz.body === undefined || opz.body === null) ? null : String(opz.body),
callback: null,
errore: null
corpo: (opz.body === undefined || opz.body === null) ? null : String(opz.body)
};
__richieste.push(richiesta);
var oggetto = {
then: function (fn) { richiesta.callback = fn; return oggetto; },
catch: function (fn) { richiesta.errore = fn; return oggetto; }
};
return oggetto;
return new Promise(function (resolve, reject) {
richiesta.resolve = resolve;
richiesta.reject = reject;
});
}
function __richieste_pendenti() {
@@ -214,18 +214,20 @@ function __risposta(id, stato, corpo) {
var r = __richieste[i];
__richieste.splice(i, 1);
if (stato < 0) {
if (r.errore) { try { r.errore({ message: 'richiesta fallita' }); } catch (e) { __log(String(e)); } }
if (r.reject) { r.reject(new Error('richiesta fallita')); }
return 1;
}
if (!r.callback) { return 0; }
var risposta = {
ok: stato >= 200 && stato < 300,
status: stato,
url: r.url,
text: function () { return corpo; },
json: function () { return JSON.parse(corpo); }
headers: { get: function () { return null; }, has: function () { return false; } },
text: function () { return Promise.resolve(corpo); },
json: function () {
return Promise.resolve(corpo).then(function (t) { return JSON.parse(t); });
}
};
try { r.callback(risposta); } catch (e) { __log('errore nel gestore di fetch: ' + e); }
if (r.resolve) { r.resolve(risposta); }
return 1;
}
@@ -1392,6 +1394,9 @@ impl Macchina {
if let Err(e) = self.ctx.eval(Source::from_bytes(codice.as_str())) {
errori.push(format!("script #{}: {}", i + 1, e));
}
// le continuazioni delle Promise (then/await) sono microtask: senza
// questo restano in coda per sempre e la pagina non si aggiorna
self.ctx.run_jobs();
}
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
applica(doc, ops);
@@ -1410,6 +1415,9 @@ impl Macchina {
if let Err(e) = self.ctx.eval(Source::from_bytes(codice.as_str())) {
errori.push(format!("script #{}: {}", i + 1, e));
}
// le continuazioni delle Promise (then/await) sono microtask: senza
// questo restano in coda per sempre e la pagina non si aggiorna
self.ctx.run_jobs();
}
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
applica(doc, ops);
@@ -1451,6 +1459,8 @@ impl Macchina {
}
}
}
// il gestore può aver acceso una Promise: le sue continuazioni girano ora
self.ctx.run_jobs();
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
applica(doc, ops);
eseguiti
@@ -1479,6 +1489,7 @@ impl Macchina {
0
}
};
self.ctx.run_jobs();
if eseguiti > 0 {
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
applica(doc, ops);
@@ -1537,6 +1548,8 @@ impl Macchina {
0
}
};
// la risposta sblocca `await fetch(...)`: le continuazioni girano adesso
self.ctx.run_jobs();
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
applica(doc, ops);
eseguiti
@@ -2060,10 +2073,14 @@ mod tests {
#[test]
fn fetch_accoda_e_la_risposta_esegue_il_callback() {
// `r.text()` restituisce una Promise, come nel browser: la catena è
// annidata, e questo test difende proprio quello (prima era sincrona)
let mut built = treebuilder::parse(
"<div id=\"t\">vuoto</div><script>\
fetch('/dati.json').then(function (r) {\
document.getElementById('t').textContent = 'stato ' + r.status + ': ' + r.text();\
return r.text().then(function (t) {\
document.getElementById('t').textContent = 'stato ' + r.status + ': ' + t;\
});\
});</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
+192
View File
@@ -0,0 +1,192 @@
//! Promise vere, `await` e `fetch` (M2.5, residuo chiuso).
//!
//! Il difetto che questi test difendono: le Promise di Boa esistevano già, ma
//! nessuno svuotava la coda dei microtask, quindi ogni `.then` restava in coda
//! per sempre e la pagina non si aggiornava — senza nessun errore da leggere.
use engine::dom::NodeKind;
use engine::script::Macchina;
use engine::ContenutoPagina;
/// Testo visibile dentro l'elemento con quell'id.
fn testo_di(contenuto: &ContenutoPagina, id: &str) -> String {
let mut nodo = None;
for (i, n) in contenuto.doc.nodes.iter().enumerate() {
if let NodeKind::Element(e) = &n.kind {
if e.attr("id") == Some(id) {
nodo = Some(i);
break;
}
}
}
let Some(nodo) = nodo else {
return String::new();
};
let mut out = String::new();
for figlio in &contenuto.doc.node(nodo).children {
if let NodeKind::Text(t) = &contenuto.doc.node(*figlio).kind {
out.push_str(t);
}
}
out
}
fn esegui(html: &str) -> (ContenutoPagina, Macchina) {
let mut contenuto = ContenutoPagina::da_html(html);
let mut macchina = Macchina::nuova().expect("interprete");
let errori = contenuto.esegui_script(&mut macchina);
assert!(errori.is_empty(), "errori negli script: {:?}", errori);
(contenuto, macchina)
}
#[test]
fn then_di_una_promise_modifica_la_pagina() {
let (contenuto, _) = esegui(
"<html><body><div id=\"a\">prima</div><script>\
Promise.resolve('dopo').then(function (v) {\
document.getElementById('a').textContent = v; });\
</script></body></html>",
);
assert_eq!(
testo_di(&contenuto, "a"),
"dopo",
"il .then non è mai girato: la coda dei microtask non viene svuotata"
);
}
#[test]
fn await_in_una_funzione_async() {
let (contenuto, _) = esegui(
"<html><body><div id=\"a\">prima</div><script>\
async function vai() {\
var uno = await Promise.resolve('uno');\
var due = await Promise.resolve('due');\
document.getElementById('a').textContent = uno + '-' + due;\
}\
vai();\
</script></body></html>",
);
assert_eq!(
testo_di(&contenuto, "a"),
"uno-due",
"await non prosegue: mancano i microtask o le Promise non sono vere"
);
}
#[test]
fn fetch_e_una_promise_e_await_ne_legge_il_corpo() {
let html = "<html><body><div id=\"a\">vuoto</div><script>\
async function vai() {\
var r = await fetch('/dati');\
var testo = await r.text();\
document.getElementById('a').textContent = r.status + ':' + testo;\
}\
vai();\
</script></body></html>";
let (mut contenuto, mut macchina) = esegui(html);
// la richiesta è in coda: la esegue il guscio, non il motore
let richieste = macchina.richieste_pendenti();
assert_eq!(richieste.len(), 1, "la fetch non si è accodata");
assert_eq!(richieste[0].1, "/dati");
assert_eq!(richieste[0].2, "GET");
// nulla è ancora cambiato: la Promise non è risolta
assert_eq!(testo_di(&contenuto, "a"), "vuoto");
let id = richieste[0].0;
assert_eq!(
macchina.consegna_risposta(&mut contenuto.doc, id, 200, "corpo vero"),
1,
"la consegna deve sbloccare la Promise"
);
assert_eq!(
testo_di(&contenuto, "a"),
"200:corpo vero",
"await r.text() non ha ripreso dopo la consegna"
);
}
#[test]
fn fetch_rifiutata_finisce_nel_catch() {
let html = "<html><body><div id=\"a\">vuoto</div><script>\
fetch('/rotto').then(function () {\
document.getElementById('a').textContent = 'non doveva riuscire';\
}).catch(function (e) {\
document.getElementById('a').textContent = 'errore: ' + e.message;\
});\
</script></body></html>";
let (mut contenuto, mut macchina) = esegui(html);
let richieste = macchina.richieste_pendenti();
let id = richieste[0].0;
// stato negativo: richiesta fallita
macchina.consegna_risposta(&mut contenuto.doc, id, -1, "");
assert_eq!(
testo_di(&contenuto, "a"),
"errore: richiesta fallita",
"una fetch fallita deve passare dal catch, non lasciare la pagina muta"
);
}
#[test]
fn json_e_promise_all() {
let html = "<html><body><div id=\"a\">vuoto</div><script>\
Promise.all([Promise.resolve(1), Promise.resolve(2)]).then(function (v) {\
document.getElementById('a').textContent = 'somma ' + (v[0] + v[1]);\
});\
</script></body></html>";
let (contenuto, _) = esegui(html);
assert_eq!(
testo_di(&contenuto, "a"),
"somma 3",
"Promise.all non funziona: le Promise non sono quelle del motore"
);
}
#[test]
fn json_di_fetch_legge_il_corpo_come_oggetto() {
let html = "<html><body><div id=\"a\">vuoto</div><script>\
async function vai() {\
var r = await fetch('/json');\
var dati = await r.json();\
document.getElementById('a').textContent = 'nome=' + dati.nome;\
}\
vai();\
</script></body></html>";
let (mut contenuto, mut macchina) = esegui(html);
let id = macchina.richieste_pendenti()[0].0;
macchina.consegna_risposta(&mut contenuto.doc, id, 200, "{\"nome\":\"Mosaic\"}");
assert_eq!(testo_di(&contenuto, "a"), "nome=Mosaic");
}
#[test]
fn then_dentro_un_gestore_di_clic() {
// il caso che rompeva il desktop: una Promise accesa da un evento
let html = concat!(
"<html><body><div id=\"riquadro\" style=\"width:60px;height:40px;background:#0000ff\">",
"<span id=\"a\">prima</span></div><script>",
"document.getElementById('riquadro').addEventListener('click', function () {",
" Promise.resolve().then(function () {",
" document.getElementById('a').textContent = 'dopo il clic';",
" });",
"});",
"</script></body></html>"
);
let (mut contenuto, mut macchina) = esegui(html);
let nodo = {
let mut trovato = 0;
for (i, n) in contenuto.doc.nodes.iter().enumerate() {
if let NodeKind::Element(e) = &n.kind {
if e.attr("id") == Some("riquadro") {
trovato = i;
}
}
}
trovato
};
let rami = engine::layout::catena_antenati(&contenuto.doc, nodo);
macchina.clic(&mut contenuto.doc, &rami, 5.0, 5.0);
assert_eq!(testo_di(&contenuto, "a"), "dopo il clic");
}
+6 -1
View File
@@ -1,6 +1,6 @@
Name: harbour-mosaic
Summary: Mosaic browser with an independent rendering engine
Version: 0.8.10
Version: 0.8.11
Release: 1
Group: Qt/Qt
License: MIT
@@ -21,6 +21,11 @@ engine written from scratch (no WebKit, Blink, Gecko or Servo code).
Milestone M0: HTML parsing, CSS cascade, block layout and CPU raster.
%changelog
* Thu Nov 12 2026 Carlo Baratto <carlo@carlobaratto.it> - 0.8.11-1
- Promise vere e await: fetch restituisce una Promise del motore, text()/json()
anche, e i microtask vengono svuotati dopo script, eventi, timer e consegna
delle risposte. Prima ogni .then restava in coda per sempre, senza errori
* Thu Nov 12 2026 Carlo Baratto <carlo@carlobaratto.it> - 0.8.10-1
- Rete: HTTP/2 con HPACK (tabelle generate dalla RFC 7541), negoziato via ALPN
- Proxy http_proxy/https_proxy/no_proxy con tunnel CONNECT