From 6a14853d0d18ff6ef9e52f39fc92f80bf6226beb Mon Sep 17 00:00:00 2001 From: Carlo Baratto Date: Fri, 13 Nov 2026 09:01:26 +0100 Subject: [PATCH] Promise vere e await: la coda dei microtask viene svuotata MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- desktop/src/main.rs | 8 ++ docs/10-roadmap.md | 2 +- engine/README.md | 1 + engine/src/script_boa.rs | 49 ++++--- engine/tests/promise.rs | 192 +++++++++++++++++++++++++ harbour-mosaic/rpm/harbour-mosaic.spec | 7 +- 6 files changed, 241 insertions(+), 18 deletions(-) create mode 100644 engine/tests/promise.rs diff --git a/desktop/src/main.rs b/desktop/src/main.rs index 27b87ad..73155a0 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -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) { diff --git a/docs/10-roadmap.md b/docs/10-roadmap.md index 99757cd..a2760ad 100644 --- a/docs/10-roadmap.md +++ b/docs/10-roadmap.md @@ -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 | diff --git a/engine/README.md b/engine/README.md index 992f19f..db6ec12 100644 --- a/engine/README.md +++ b/engine/README.md @@ -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 | — | diff --git a/engine/src/script_boa.rs b/engine/src/script_boa.rs index 9c0172c..5b202f3 100644 --- a/engine/src/script_boa.rs +++ b/engine/src/script_boa.rs @@ -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( "
vuoto
", ); let mut macchina = Macchina::nuova().expect("interprete"); diff --git a/engine/tests/promise.rs b/engine/tests/promise.rs new file mode 100644 index 0000000..994aa1c --- /dev/null +++ b/engine/tests/promise.rs @@ -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( + "
prima
", + ); + 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( + "
prima
", + ); + 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 = "
vuoto
"; + + 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 = "
vuoto
"; + + 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 = "
vuoto
"; + 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 = "
vuoto
"; + 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!( + "
", + "prima
" + ); + 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"); +} diff --git a/harbour-mosaic/rpm/harbour-mosaic.spec b/harbour-mosaic/rpm/harbour-mosaic.spec index 55b571a..c591215 100644 --- a/harbour-mosaic/rpm/harbour-mosaic.spec +++ b/harbour-mosaic/rpm/harbour-mosaic.spec @@ -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 - 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 - 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