gui: native WebView host as nested module yetano.dev/yetano/core/gui

Extracted from prototypes/yetano-webview (AP1): packages assets,
document, bridge and window (macOS Cocoa/WKWebView via cgo, Windows
Win32/WebView2 pure Go). No local HTTP listener or port: assets go
through the WebView's resource handler, app routes through the native
message binding. Own go.mod and gui/vX.Y.Z tags keep cgo and the
WebView dependencies out of the main core module. Adds backend-free
tests for the window's dispatch/destroy guards and a yet-gui migration
guide.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
terminarandClaude Opus 5.5 committed 2026-10-23 14:47:26 +02:00
1 parent 90132e2d76
commit 8c63d42a27
27 files changed
+4849 -3

No files matched your search

+422
View File
@@ -0,0 +1,422 @@
// Yetano WebView bridge, protocol v1. Installed as a document-start script
// before any page script. Replaces window.fetch and window.XMLHttpRequest for
// page-local URLs ("/..." and "assets:...") and routes them through the single
// native binding __yetano_post to the Go host. No network listener is used.
(function () {
'use strict';
if (window.yetano && window.yetano.__installed) return;
window.__yetano_install_count = (window.__yetano_install_count || 0) + 1;
var cfg = window.__yetano_config || {};
var PROTO = 1;
var origFetch = typeof window.fetch === 'function' ? window.fetch.bind(window) : null;
var OrigXHR = window.XMLHttpRequest;
var nonce = Math.random().toString(36).slice(2) + Date.now().toString(36);
var gen = 0;
var seq = 0;
var pending = new Map();
var stats = { staleDropped: 0, requests: 0 };
var readyResolve, readyReject, readySettled = false;
var ready = new Promise(function (res, rej) { readyResolve = res; readyReject = rej; });
ready.catch(function () {}); // the rejection is reported to callers, not as unhandled
function settleReady(ok, v) {
if (readySettled) return;
readySettled = true;
clearTimeout(helloTimer);
(ok ? readyResolve : readyReject)(v);
}
function post(msg) {
var fn = window.__yetano_post;
if (typeof fn !== 'function') return Promise.reject(new Error('native binding __yetano_post missing'));
try { return Promise.resolve(fn(msg)); } catch (e) { return Promise.reject(e); }
}
// ---- receive ---------------------------------------------------------
window.__yetano_recv = function (m) {
if (!m || typeof m !== 'object') return;
if (m.t === 'ready') {
if (m.nonce !== nonce) return;
if (m.error) { settleReady(false, new Error('yetano bridge: ' + m.error)); return; }
gen = m.gen;
settleReady(true, { generation: m.gen, session: m.session, protocol: m.v });
return;
}
if (m.t !== 'res' && m.t !== 'err' && m.t !== 'chunk' && m.t !== 'end') return;
var p = pending.get(m.id);
if (!p || m.gen !== gen) { stats.staleDropped++; return; }
switch (m.t) {
case 'res':
if (m.stream) p.startStream(m);
else p.resolve({ status: m.status, statusText: m.statusText || '', headers: m.headers || {}, body: b64dec(m.body || '') });
break;
case 'chunk': p.chunk(b64dec(m.data || '')); break;
case 'end': p.end(); break;
default: {
var e = m.code === 'timeout' ? new DOMException('yetano: ' + m.message, 'TimeoutError')
: m.code === 'abort' ? new DOMException('yetano: ' + m.message, 'AbortError')
: new TypeError('yetano bridge ' + m.code + ': ' + m.message);
p.fail(e);
}
}
};
var helloTimer = setTimeout(function () {
settleReady(false, new Error('yetano bridge: handshake timed out'));
}, cfg.handshakeTimeoutMs || 5000);
post({ t: 'hello', v: cfg.protocolOverride || PROTO, nonce: nonce }).catch(function (e) {
settleReady(false, new Error('yetano bridge: hello failed: ' + e));
});
// ---- helpers ---------------------------------------------------------
function b64enc(u8) {
var s = '';
for (var i = 0; i < u8.length; i += 0x8000) {
s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000));
}
return btoa(s);
}
function b64dec(s) {
var bin = atob(s);
var u8 = new Uint8Array(bin.length);
for (var i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
return u8;
}
function abortError(signal) {
return (signal && signal.reason !== undefined) ? signal.reason : new DOMException('The operation was aborted.', 'AbortError');
}
// Local URLs are recognized on the raw string, before any URL() resolution
// (an inline entry document has an opaque data: origin). Absolute URLs on
// the app origin (native transport) count as local, too.
var NATIVE = cfg.transport === 'native';
function localURL(u) {
if (typeof u !== 'string') return null;
if (u.indexOf('assets:') === 0) return u;
if (cfg.origin && u.indexOf(cfg.origin + '/') === 0) return u.slice(cfg.origin.length);
if (u.charAt(0) === '/' && u.charAt(1) !== '/') return u;
return null;
}
// For the native transport: "assets:x" is not loadable by the browser.
function nativeURL(local) {
return local.indexOf('assets:') === 0 ? '/assets/' + local.slice(7) : local;
}
function externalBlocked(u) {
return new TypeError('yetano: external request blocked by policy: ' + u);
}
async function toBytes(body, headers) {
function setType(t) { if (!headers['content-type']) headers['content-type'] = t; }
if (typeof body === 'string') { setType('text/plain;charset=UTF-8'); return new TextEncoder().encode(body); }
if (body instanceof URLSearchParams) { setType('application/x-www-form-urlencoded;charset=UTF-8'); return new TextEncoder().encode(body.toString()); }
if (body instanceof ArrayBuffer) return new Uint8Array(body);
if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
if (typeof Blob !== 'undefined' && body instanceof Blob) { if (body.type) setType(body.type); return new Uint8Array(await body.arrayBuffer()); }
if (typeof FormData !== 'undefined' && body instanceof FormData) {
// Let the browser produce multipart/form-data (with its boundary).
var mp = new Response(body);
headers['content-type'] = mp.headers.get('content-type');
return new Uint8Array(await mp.arrayBuffer());
}
if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) throw new TypeError('yetano: streaming request bodies are not supported (AP1 limit)');
setType('text/plain;charset=UTF-8');
return new TextEncoder().encode(String(body));
}
// request sends one call. The promise settles exactly once: with the
// response head (body bytes, or a ReadableStream for streamed responses)
// or with an error (abort, timeout, stale generation, transport). A stream
// ends exactly once, too: end, error, abort or reader cancel. Every end
// that is not initiated by Go is reported to Go (abort message).
async function request(d) {
await ready;
if (d.signal && d.signal.aborted) throw abortError(d.signal);
var id = String(++seq);
var myGen = gen;
stats.requests++;
return new Promise(function (resolve, reject) {
var timer = null, ctrl = null, settled = false;
function cleanup() {
pending.delete(id);
if (timer) { clearTimeout(timer); timer = null; }
if (d.signal) d.signal.removeEventListener('abort', onAbort);
}
function fail(e) {
if (!pending.has(id)) return;
cleanup();
if (ctrl) { try { ctrl.error(e); } catch (x) {} } else if (!settled) { settled = true; reject(e); }
}
function onAbort() { fail(abortError(d.signal)); post({ t: 'abort', id: id, gen: myGen }); }
pending.set(id, {
resolve: function (v) { if (!pending.has(id)) return; cleanup(); settled = true; resolve(v); },
fail: fail,
startStream: function (m) {
if (timer) { clearTimeout(timer); timer = null; } // the timeout covers the response head
var body = new ReadableStream({
start: function (c) { ctrl = c; },
cancel: function () { if (!pending.has(id)) return; cleanup(); post({ t: 'abort', id: id, gen: myGen }); }
});
settled = true;
resolve({ status: m.status, statusText: m.statusText || '', headers: m.headers || {}, body: body, streaming: true });
},
chunk: function (u8) { if (ctrl) ctrl.enqueue(u8); },
end: function () { if (!pending.has(id)) return; cleanup(); if (ctrl) ctrl.close(); }
});
if (d.signal) d.signal.addEventListener('abort', onAbort, { once: true });
var t = d.timeoutMs != null ? d.timeoutMs : (cfg.defaultTimeoutMs || 30000);
if (t > 0) {
timer = setTimeout(function () {
fail(new DOMException('yetano: request timed out after ' + t + ' ms', 'TimeoutError'));
post({ t: 'abort', id: id, gen: myGen, reason: 'timeout' });
}, t);
}
post({
t: 'req', id: id, gen: myGen, method: d.method, url: d.url, headers: d.headers,
body: d.body ? b64enc(d.body) : null, timeoutMs: t
}).catch(function (e) { fail(new TypeError('yetano bridge: transport failed: ' + e)); });
});
}
// ---- fetch -----------------------------------------------------------
// bridgeFetch: local requests as bridge messages (abort, timeout and
// document generation reach the Go handler; bodies are buffered).
async function bridgeFetch(input, init) {
init = init || {};
var url = typeof input === 'string' ? input
: (typeof URL !== 'undefined' && input instanceof URL) ? input.href
: (input && input.url);
var local = localURL(url);
if (local === null) {
if (cfg.external === 'passthrough' && origFetch) return origFetch(input, init);
throw externalBlocked(url);
}
var method = String(init.method || 'GET').toUpperCase();
var headers = {};
new Headers(init.headers || {}).forEach(function (v, k) { headers[k] = v; });
var body = null;
if (init.body != null) {
if (method === 'GET' || method === 'HEAD') throw new TypeError('yetano: ' + method + ' request cannot have a body');
body = await toBytes(init.body, headers);
}
var r = await request({ method: method, url: local, headers: headers, body: body, signal: init.signal, timeoutMs: init.yetanoTimeout });
var nullBody = method === 'HEAD' || r.status === 204 || r.status === 205 || r.status === 304;
return new Response(nullBody ? null : r.body, { status: r.status, statusText: r.statusText, headers: r.headers });
}
bridgeFetch.yetano = true;
// nativeFetch (native transport): assets come from the native resource
// handler (no size limit, real Response, ES modules); app routes use the
// bridge (abort/timeout/generation reach Go, streaming via chunk messages
// on every backend). init.yetanoTransport = 'native' | 'bridge' overrides.
function isAsset(local) { return local.indexOf('assets:') === 0 || local.indexOf('/assets/') === 0; }
async function nativeFetch(input, init) {
var url = typeof input === 'string' ? input
: (typeof URL !== 'undefined' && input instanceof URL) ? input.href
: (input && input.url);
var local = localURL(url);
if (local === null) {
if (cfg.external === 'passthrough') return origFetch(input, init);
throw externalBlocked(url);
}
var via = (init && init.yetanoTransport) || (isAsset(local) ? 'native' : 'bridge');
if (via === 'bridge') return bridgeFetch(input, init);
if (typeof input === 'string' || (typeof URL !== 'undefined' && input instanceof URL)) input = nativeURL(local);
// WebKit hands Blob/FormData bodies to a URL scheme handler as empty
// (observed); serialize them here so every backend receives the bytes.
if (init && needsSerialize(init.body)) {
var headers = {};
new Headers(init.headers || {}).forEach(function (v, k) { headers[k] = v; });
var bytes = await toBytes(init.body, headers);
init = Object.assign({}, init, { body: bytes, headers: headers });
}
return origFetch(input, init);
}
nativeFetch.yetano = true;
function needsSerialize(b) {
return b != null && ((typeof Blob !== 'undefined' && b instanceof Blob) || (typeof FormData !== 'undefined' && b instanceof FormData));
}
var yetanoFetch = NATIVE ? nativeFetch : bridgeFetch;
window.fetch = yetanoFetch;
// ---- XMLHttpRequest -------------------------------------------------
// Local URLs go through the bridge (native transport: assets through the
// real XHR from the app origin); external URLs are delegated to the real
// XHR only with cfg.external === 'passthrough'. Re-opening or aborting an
// instance invalidates its earlier call (token), so a late reply for an old
// request never lands in the reused object.
function YetanoXHR() {
var et = new EventTarget();
this._et = et;
this.upload = new EventTarget();
this.readyState = 0; this.status = 0; this.statusText = '';
this.response = null; this.responseText = ''; this.responseType = ''; this.responseURL = '';
this.timeout = 0; this.withCredentials = false;
this._token = 0; this._reqHeaders = {}; this._respHeaders = {}; this._ctl = null; this._sent = false;
}
YetanoXHR.UNSENT = 0; YetanoXHR.OPENED = 1; YetanoXHR.HEADERS_RECEIVED = 2; YetanoXHR.LOADING = 3; YetanoXHR.DONE = 4;
['UNSENT', 'OPENED', 'HEADERS_RECEIVED', 'LOADING', 'DONE'].forEach(function (k, i) { YetanoXHR.prototype[k] = i; });
YetanoXHR.prototype.addEventListener = function (t, f, o) { this._et.addEventListener(t, f, o); };
YetanoXHR.prototype.removeEventListener = function (t, f, o) { this._et.removeEventListener(t, f, o); };
YetanoXHR.prototype.dispatchEvent = function (e) { return this._et.dispatchEvent(e); };
YetanoXHR.prototype._fire = function (type, loaded, total) {
var ev = (type === 'readystatechange') ? new Event(type)
: new ProgressEvent(type, { lengthComputable: total != null, loaded: loaded || 0, total: total || 0 });
var h = this['on' + type];
if (typeof h === 'function') { try { h.call(this, ev); } catch (e) { setTimeout(function () { throw e; }); } }
this._et.dispatchEvent(ev);
};
YetanoXHR.prototype._state = function (s) { this.readyState = s; this._fire('readystatechange'); };
YetanoXHR.prototype.open = function (method, url, async) {
if (async === false) throw new DOMException('yetano: synchronous XMLHttpRequest is not supported', 'InvalidAccessError');
this._token++;
if (this._ctl) { this._ctl.abort(); this._ctl = null; }
if (this._native) { this._native.abort(); this._native = null; }
this._method = String(method || 'GET').toUpperCase();
this._url = String(url);
this._reqHeaders = {}; this._respHeaders = {}; this._sent = false;
this.status = 0; this.statusText = ''; this.response = null; this.responseText = '';
this._state(1);
};
YetanoXHR.prototype.setRequestHeader = function (k, v) {
if (this.readyState !== 1 || this._sent) throw new DOMException('setRequestHeader: invalid state', 'InvalidStateError');
k = String(k).toLowerCase();
this._reqHeaders[k] = this._reqHeaders[k] ? this._reqHeaders[k] + ', ' + v : String(v);
};
YetanoXHR.prototype.overrideMimeType = function (m) { this._mime = m; };
YetanoXHR.prototype.getResponseHeader = function (k) {
var v = this._respHeaders[String(k).toLowerCase()];
return v === undefined ? null : v;
};
YetanoXHR.prototype.getAllResponseHeaders = function () {
var h = this._respHeaders;
return Object.keys(h).sort().map(function (k) { return k + ': ' + h[k] + '\r\n'; }).join('');
};
YetanoXHR.prototype.abort = function () {
var wasActive = this._sent && this.readyState !== 4;
this._token++;
if (this._ctl) { this._ctl.abort(); this._ctl = null; }
if (this._native) { this._native.abort(); this._native = null; }
if (wasActive) { this._sent = false; this._state(4); this._fire('abort'); this._fire('loadend'); }
this.readyState = 0;
};
YetanoXHR.prototype.send = function (body) {
if (this.readyState !== 1 || this._sent) throw new DOMException('send: invalid state', 'InvalidStateError');
var self = this, token = this._token;
var local = localURL(this._url);
if (local === null) return this._sendNative(body, false);
if (NATIVE && isAsset(local)) return this._sendNative(body, true, nativeURL(local));
this._sent = true;
var ctl = new AbortController();
this._ctl = ctl;
var headers = Object.assign({}, this._reqHeaders);
this._fire('loadstart', 0);
(async function () {
var bytes = null;
if (body != null && self._method !== 'GET' && self._method !== 'HEAD') bytes = await toBytes(body, headers);
return request({ method: self._method, url: local, headers: headers, body: bytes, signal: ctl.signal, timeoutMs: self.timeout > 0 ? self.timeout : undefined });
})().then(async function (r) {
if (r.streaming) r.body = new Uint8Array(await new Response(r.body).arrayBuffer());
return r;
}).then(function (r) {
if (token !== self._token) return; // reopened/aborted meanwhile
self._ctl = null;
self.status = r.status; self.statusText = r.statusText; self._respHeaders = r.headers;
self.responseURL = local;
self._state(2);
var type = (self._mime || r.headers['content-type'] || '').split(';')[0].trim();
var text = null;
function asText() { if (text === null) text = new TextDecoder().decode(r.body); return text; }
switch (self.responseType) {
case 'arraybuffer': self.response = r.body.buffer.slice(r.body.byteOffset, r.body.byteOffset + r.body.byteLength); break;
case 'blob': self.response = new Blob([r.body], { type: type }); break;
case 'json': try { self.response = JSON.parse(asText()); } catch (e) { self.response = null; } break;
case 'document': self.response = new DOMParser().parseFromString(asText(), type === 'text/xml' || type === 'application/xml' ? type : 'text/html'); break;
default: self.responseText = self.response = asText();
}
self._state(3);
self._fire('progress', r.body.length, r.body.length);
self._sent = false;
self._state(4);
self._fire('load', r.body.length, r.body.length);
self._fire('loadend', r.body.length, r.body.length);
}, function (e) {
if (token !== self._token) return;
self._ctl = null; self._sent = false;
self.status = 0;
self._state(4);
self._fire(e && e.name === 'TimeoutError' ? 'timeout' : (e && e.name === 'AbortError' ? 'abort' : 'error'));
self._fire('loadend');
});
};
YetanoXHR.prototype._sendNative = function (body, asset, url) {
var self = this;
if (!asset && (cfg.external !== 'passthrough' || !OrigXHR)) {
this._sent = true;
setTimeout(function () {
self._sent = false; self.status = 0; self._state(4);
self._fire('error'); self._fire('loadend');
if (window.console) console.warn(String(externalBlocked(self._url)));
});
return;
}
var x = new OrigXHR();
this._native = x;
this._sent = true;
x.open(this._method, url || this._url, true);
Object.keys(this._reqHeaders).forEach(function (k) { x.setRequestHeader(k, self._reqHeaders[k]); });
x.responseType = this.responseType; x.timeout = this.timeout; x.withCredentials = this.withCredentials;
['readystatechange', 'loadstart', 'progress', 'load', 'error', 'abort', 'timeout', 'loadend'].forEach(function (t) {
x.addEventListener(t, function () {
if (self._native !== x) return;
self.status = x.status; self.statusText = x.statusText; self.response = x.response; self.responseURL = x.responseURL;
if (x.responseType === '' || x.responseType === 'text') self.responseText = x.responseText;
self._respHeaders = {};
(x.getAllResponseHeaders() || '').trim().split(/[\r\n]+/).forEach(function (l) {
var i = l.indexOf(':'); if (i > 0) self._respHeaders[l.slice(0, i).trim().toLowerCase()] = l.slice(i + 1).trim();
});
if (t === 'readystatechange') { self._state(x.readyState); } else { self._fire(t); }
});
});
x.send(body);
};
window.XMLHttpRequest = YetanoXHR;
// ---- page console -> host log (diagnostics) ---------------------------
if (cfg.forwardConsole) {
['log', 'warn', 'error'].forEach(function (lvl) {
var orig = console[lvl];
console[lvl] = function () {
try { post({ t: 'log', level: lvl, msg: Array.prototype.map.call(arguments, String).join(' ') }); } catch (e) {}
return orig.apply(console, arguments);
};
});
window.addEventListener('error', function (e) { post({ t: 'log', level: 'error', msg: 'uncaught: ' + e.message + ' @' + e.filename + ':' + e.lineno }); });
window.addEventListener('unhandledrejection', function (e) { post({ t: 'log', level: 'error', msg: 'unhandled rejection: ' + (e.reason && e.reason.stack || e.reason) }); });
}
// ---- public API ------------------------------------------------------
async function call(route, payload, opts) {
opts = opts || {};
var r = await bridgeFetch('/rpc/' + route, {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload === undefined ? null : payload),
signal: opts.signal, yetanoTimeout: opts.timeoutMs
});
var text = await r.text();
if (!r.ok) { var err = new Error(route + ': HTTP ' + r.status + ': ' + text); err.status = r.status; throw err; }
return text ? JSON.parse(text) : null;
}
window.yetano = Object.freeze({
__installed: true,
protocol: PROTO,
config: cfg,
transport: NATIVE ? 'native' : 'inline',
bridgeFetch: bridgeFetch,
ready: ready,
fetch: yetanoFetch,
call: call,
pendingCount: function () { return pending.size; },
stats: function () { return { staleDropped: stats.staleDropped, requests: stats.requests, pending: pending.size, generation: gen }; },
_post: cfg.selftest ? post : undefined
});
})();
+72
View File
@@ -0,0 +1,72 @@
package bridge
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
)
// NativeWriter is the response side of a native resource request
// (implemented by window.ResourceWriter).
type NativeWriter interface {
Respond(status int, header http.Header)
Write(p []byte) (int, error)
Close(err error)
}
// ServeNative answers a request the WebView made to the app origin through
// the native resource handler: "/" is the entry document, everything else
// goes through the same router as bridge requests. Stream responses are
// written through as they are produced.
func (r *Router) ServeNative(ctx context.Context, origin, method, rawURL string, header http.Header, body []byte, w NativeWriter) {
if !strings.HasPrefix(rawURL, origin+"/") {
w.Respond(http.StatusForbidden, textHeader())
w.Write([]byte("not the app origin: " + rawURL))
return
}
local := rawURL[len(origin):]
path, q, err := ParseLocalURL(local)
if err != nil {
w.Respond(http.StatusBadRequest, textHeader())
w.Write([]byte(err.Error()))
return
}
if path == "/" {
r.mu.RLock()
entry := r.entry
r.mu.RUnlock()
path = "/assets/" + entry
}
req := &Request{Native: true, Method: strings.ToUpper(method), URL: local, Path: path, Query: q, Header: header, Body: body}
resp, err := r.Serve(ctx, req)
if err != nil {
w.Close(err)
return
}
h := resp.Header
if h == nil {
h = http.Header{}
}
h.Set("Cache-Control", "no-store")
w.Respond(resp.Status, h)
if resp.Stream != nil {
if err := resp.Stream(ctx, w); err != nil && !errors.Is(err, context.Canceled) {
w.Close(fmt.Errorf("%s %s: stream: %w", req.Method, req.Path, err))
return
}
w.Close(nil)
return
}
if len(resp.Body) > 0 {
w.Write(resp.Body)
}
w.Close(nil)
}
func textHeader() http.Header {
h := http.Header{}
h.Set("Content-Type", "text/plain; charset=utf-8")
return h
}
+265
View File
@@ -0,0 +1,265 @@
package bridge
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"runtime/debug"
"sort"
"strings"
"sync"
"yetano.dev/yetano/core/gui/assets"
"yetano.dev/yetano/core/gui/document"
)
// Request is a local request as it arrives from the fetch/XHR adapter or
// the native resource handler.
type Request struct {
Native bool // via the native resource handler (link mode for HTML/CSS)
Method string
URL string // as written by the page ("/rpc/add?x=1", "assets:img/a.png")
Path string // percent-decoded once, without query
Query url.Values
Header http.Header
Body []byte
}
// Response is an HTTP-like local response. 404/500 are responses, not
// transport errors. A handler either sets Body or Stream. Stream writes the
// body incrementally: the native resource handler delivers every Write to
// the page as it happens; the bridge transport buffers it (MaxBody).
type Response struct {
Status int
Header http.Header
Body []byte
Stream func(ctx context.Context, w io.Writer) error
}
// HandlerFunc serves one registered route. Returning an error yields a 500
// response that names the route; a cancelled ctx yields an abort/timeout.
type HandlerFunc func(ctx context.Context, req *Request) (*Response, error)
// Router maps local requests to the asset resolver and to registered Go
// handlers. Routes are fixed before the document starts (Freeze).
type Router struct {
mu sync.RWMutex
routes map[string]HandlerFunc // "METHOD /path"
frozen bool
res *assets.Resolver
entry string // asset served for "/" by the native handler
native bool // document mode: link (native) or inline (bridge)
}
// SetDocument sets the entry asset for "/" and whether Go-generated HTML is
// prepared for the native resource handler (link mode) or inlined.
func (r *Router) SetDocument(entry string, native bool) {
r.mu.Lock()
r.entry, r.native = entry, native
r.mu.Unlock()
}
// NewRouter creates a router that serves GET/HEAD /assets/... and assets:...
// from res.
func NewRouter(res *assets.Resolver) *Router {
return &Router{routes: map[string]HandlerFunc{}, res: res}
}
// Resolver returns the asset resolver behind /assets/.
func (r *Router) Resolver() *assets.Resolver { return r.res }
// Handle registers h for an exact method and path. Duplicate registrations
// and registrations after Freeze are errors.
func (r *Router) Handle(method, path string, h HandlerFunc) error {
method = strings.ToUpper(method)
if !strings.HasPrefix(path, "/") || strings.HasPrefix(path, "/assets/") || h == nil {
return fmt.Errorf("bridge: invalid route %s %s", method, path)
}
key := method + " " + path
r.mu.Lock()
defer r.mu.Unlock()
if r.frozen {
return fmt.Errorf("bridge: route %s registered after document start", key)
}
if _, dup := r.routes[key]; dup {
return fmt.Errorf("bridge: duplicate route %s", key)
}
r.routes[key] = h
return nil
}
// Freeze ends registration.
func (r *Router) Freeze() {
r.mu.Lock()
r.frozen = true
r.mu.Unlock()
}
// Routes lists registered routes (diagnostics).
func (r *Router) Routes() []string {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]string, 0, len(r.routes))
for k := range r.routes {
out = append(out, k)
}
sort.Strings(out)
return out
}
// ParseLocalURL splits a page-local URL into path and query. It accepts
// "/x" (not "//x") and "assets:x". The path is percent-decoded exactly once.
func ParseLocalURL(raw string) (path string, q url.Values, err error) {
p, rest := assets.SplitRef(raw)
if strings.HasPrefix(rest, "?") {
qs := rest[1:]
if i := strings.IndexByte(qs, '#'); i >= 0 {
qs = qs[:i]
}
if q, err = url.ParseQuery(qs); err != nil {
return "", nil, fmt.Errorf("bad query: %w", err)
}
}
switch {
case strings.HasPrefix(p, assets.PrefixScheme):
p = assets.PrefixSlash + p[len(assets.PrefixScheme):]
case strings.HasPrefix(p, "/") && !strings.HasPrefix(p, "//"):
default:
return "", nil, fmt.Errorf("not a local URL: %q", raw)
}
dec, err := url.PathUnescape(p)
if err != nil {
return "", nil, fmt.Errorf("bad path escape: %w", err)
}
return dec, q, nil
}
// Serve answers one request. It returns an error only when ctx ended
// (abort, timeout, stale generation, close).
func (r *Router) Serve(ctx context.Context, req *Request) (resp *Response, err error) {
defer func() {
if p := recover(); p != nil {
resp, err = Text(http.StatusInternalServerError, fmt.Sprintf("%s %s: handler panic: %v\n%s", req.Method, req.Path, p, debug.Stack())), nil
}
}()
resp = r.serve(ctx, req)
if cerr := ctx.Err(); cerr != nil {
return nil, context.Cause(ctx)
}
return resp, nil
}
func (r *Router) serve(ctx context.Context, req *Request) *Response {
if strings.HasPrefix(req.Path, assets.PrefixSlash) {
if req.Method != http.MethodGet && req.Method != http.MethodHead {
return Text(http.StatusMethodNotAllowed, "assets are read-only")
}
name := req.Path[len(assets.PrefixSlash):]
res, err := r.res.Resolve(ctx, name)
switch {
case errors.Is(err, assets.ErrInvalidPath):
return Text(http.StatusBadRequest, err.Error())
case errors.Is(err, fs.ErrNotExist):
return Text(http.StatusNotFound, err.Error())
case err != nil:
return Text(http.StatusInternalServerError, err.Error())
}
h := http.Header{}
h.Set("Content-Type", res.MIME)
h.Set("X-Yetano-Asset-Source", res.Source)
body := res.Bytes
if req.Native {
// Natively loaded HTML/CSS: assets: references become /assets/
// URLs the WebView can load; nothing is inlined.
var err error
switch assets.BaseMIME(res.MIME) {
case "text/html":
var doc *document.Result
if doc, err = document.Prepare(ctx, r.res, name, body, document.Options{Link: true}); err == nil {
body = doc.HTML
}
case "text/css":
body, err = document.PrepareCSS(ctx, r.res, name, body, document.Options{Link: true})
}
if err != nil {
return Text(http.StatusInternalServerError, err.Error())
}
}
if req.Method == http.MethodHead {
h.Set("Content-Length", fmt.Sprint(len(body)))
body = nil
}
return &Response{Status: http.StatusOK, Header: h, Body: body}
}
r.mu.RLock()
h, ok := r.routes[req.Method+" "+req.Path]
if !ok && req.Method == http.MethodHead {
h, ok = r.routes["GET "+req.Path]
}
known := false
if !ok {
for k := range r.routes {
if strings.HasSuffix(k, " "+req.Path) {
known = true
}
}
}
r.mu.RUnlock()
if !ok {
if known {
return Text(http.StatusMethodNotAllowed, fmt.Sprintf("%s not allowed for %s", req.Method, req.Path))
}
return Text(http.StatusNotFound, "no route for "+req.Method+" "+req.Path)
}
resp, err := h(ctx, req)
if err != nil {
if ctx.Err() != nil {
return nil
}
return Text(http.StatusInternalServerError, fmt.Sprintf("%s %s: %v", req.Method, req.Path, err))
}
if resp == nil {
resp = &Response{Status: http.StatusNoContent}
}
if resp.Status < 200 || resp.Status > 599 {
return Text(http.StatusInternalServerError, fmt.Sprintf("%s %s: handler returned invalid status %d", req.Method, req.Path, resp.Status))
}
if req.Method == http.MethodHead {
resp.Body = nil
}
return resp
}
// Text builds a text/plain response.
func Text(status int, body string) *Response {
h := http.Header{}
h.Set("Content-Type", "text/plain; charset=utf-8")
return &Response{Status: status, Header: h, Body: []byte(body)}
}
// JSONBytes builds an application/json response from already-encoded JSON.
func JSONBytes(status int, body []byte) *Response {
h := http.Header{}
h.Set("Content-Type", "application/json")
return &Response{Status: status, Header: h, Body: body}
}
// HTML prepares Go-generated HTML through the same asset replace as the entry
// document and returns it as a text/html response.
func (r *Router) HTML(ctx context.Context, name string, src []byte) (*Response, error) {
r.mu.RLock()
link := r.native
r.mu.RUnlock()
doc, err := document.Prepare(ctx, r.res, name, src, document.Options{Link: link})
if err != nil {
return nil, err
}
h := http.Header{}
h.Set("Content-Type", "text/html; charset=utf-8")
return &Response{Status: http.StatusOK, Header: h, Body: doc.HTML}, nil
}
+32
View File
@@ -0,0 +1,32 @@
package bridge
import (
_ "embed"
"encoding/json"
)
//go:embed bridge.js
var bridgeJS string
// PageConfig is exposed to the page as window.__yetano_config (and
// window.yetano.config) before the bridge installs itself.
type PageConfig struct {
External string `json:"external"` // "reject" (default) or "passthrough"
Transport string `json:"transport"` // "native" (scheme handler) or "inline" (data: entry, bridge only)
Origin string `json:"origin,omitempty"`
DefaultTimeoutMs int `json:"defaultTimeoutMs,omitempty"`
HandshakeTimeoutMs int `json:"handshakeTimeoutMs,omitempty"`
ForwardConsole bool `json:"forwardConsole,omitempty"`
Selftest bool `json:"selftest,omitempty"`
Run int `json:"run,omitempty"`
ProtocolOverride int `json:"protocolOverride,omitempty"` // tests only
}
// InitScript returns the document-start script: config + bridge.
func InitScript(cfg PageConfig) string {
if cfg.External == "" {
cfg.External = "reject"
}
b, _ := json.Marshal(cfg)
return "window.__yetano_config=" + string(b) + ";\n" + bridgeJS
}
+477
View File
@@ -0,0 +1,477 @@
// Package bridge connects the page and the Go host without any network
// listener: one native binding (__yetano_post) carries JSON messages from
// JS to Go; replies go back through Dispatch+Eval on the UI thread.
//
// Protocol v1 (all messages are JSON objects with a "t" field):
//
// JS -> Go {t:"hello", v, nonce}
// JS -> Go {t:"req", id, gen, method, url, headers, body(base64|null), timeoutMs}
// JS -> Go {t:"abort", id, gen, reason}
// JS -> Go {t:"log", level, msg}
// Go -> JS {t:"ready", v, gen, nonce, session} or {t:"ready", nonce, error}
// Go -> JS {t:"res", id, gen, status, statusText, headers, body(base64)}
// Go -> JS {t:"err", id, gen, code, message} code: abort|timeout|stale|closed|protocol
//
// Every document load sends a new hello and gets a new generation. Calls of
// an older generation are cancelled and their results are dropped, both in Go
// (before Dispatch and again on the UI thread) and in JS.
package bridge
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
)
// ProtocolVersion is the bridge wire version.
const ProtocolVersion = 1
// Binding is the name of the single native binding.
const Binding = "__yetano_post"
// Cancellation causes reported to handlers via context.Cause.
var (
ErrAborted = errors.New("request aborted by page")
ErrTimeout = errors.New("request timed out")
ErrStale = errors.New("document generation replaced (reload/navigation)")
ErrClosed = errors.New("session closed")
)
// Dispatcher is the part of the native window the session needs. Dispatch
// must be safe from any goroutine and run f on the UI thread; Eval is only
// called from inside such an f.
type Dispatcher interface {
Dispatch(f func())
Eval(js string)
}
// Options configure a session.
type Options struct {
MaxBody int // max request body (decoded); default 8 MiB
MaxTimeout time.Duration // upper bound for any call; default 60s
CloseWait time.Duration // how long Close waits for handlers; default 5s
Logf func(format string, args ...any)
OnPageLog func(level, msg string)
OnHello func(gen uint64) // called after a new generation started
}
// Stats are counters for diagnostics and tests.
type Stats struct {
Generation uint64 `json:"generation"`
Hellos uint64 `json:"hellos"`
Requests uint64 `json:"requests"`
Completed uint64 `json:"completed"`
Cancelled uint64 `json:"cancelled"`
DroppedStale uint64 `json:"droppedStale"`
DroppedClosed uint64 `json:"droppedClosed"`
ProtocolErrors uint64 `json:"protocolErrors"`
Pending int `json:"pending"`
}
type call struct {
gen uint64
cancel context.CancelCauseFunc
}
// Session owns the bridge state of one window.
type Session struct {
id string
router *Router
opt Options
mu sync.Mutex
d Dispatcher
gen uint64
closed bool
calls map[string]*call
wg sync.WaitGroup
hellos, requests, completed, cancelled atomic.Uint64
droppedStale, droppedClosed, protocolErrors atomic.Uint64
}
// NewSession creates a session for router. The router is frozen.
func NewSession(router *Router, opt Options) *Session {
if opt.MaxBody == 0 {
opt.MaxBody = 8 << 20
}
if opt.MaxTimeout == 0 {
opt.MaxTimeout = 60 * time.Second
}
if opt.CloseWait == 0 {
opt.CloseWait = 5 * time.Second
}
if opt.Logf == nil {
opt.Logf = func(string, ...any) {}
}
router.Freeze()
var b [8]byte
_, _ = rand.Read(b[:])
return &Session{id: hex.EncodeToString(b[:]), router: router, opt: opt, calls: map[string]*call{}}
}
// Attach sets the dispatcher (the native window). Must happen before the
// first message.
func (s *Session) Attach(d Dispatcher) {
s.mu.Lock()
s.d = d
s.mu.Unlock()
}
// ID returns the random session id.
func (s *Session) ID() string { return s.id }
// Stats returns a snapshot of the counters.
func (s *Session) Stats() Stats {
s.mu.Lock()
gen, pending := s.gen, len(s.calls)
s.mu.Unlock()
return Stats{
Generation: gen, Hellos: s.hellos.Load(), Requests: s.requests.Load(),
Completed: s.completed.Load(), Cancelled: s.cancelled.Load(),
DroppedStale: s.droppedStale.Load(), DroppedClosed: s.droppedClosed.Load(),
ProtocolErrors: s.protocolErrors.Load(), Pending: pending,
}
}
type inMsg struct {
T string `json:"t"`
V int `json:"v"`
Nonce string `json:"nonce"`
ID string `json:"id"`
Gen uint64 `json:"gen"`
Method string `json:"method"`
URL string `json:"url"`
Headers map[string]string `json:"headers"`
Body *string `json:"body"`
TimeoutMs int64 `json:"timeoutMs"`
Reason string `json:"reason"`
Level string `json:"level"`
Msg string `json:"msg"`
}
// Post is the native binding target. It only decodes and enqueues; all work
// happens on other goroutines, so the UI thread is never blocked.
func (s *Session) Post(raw json.RawMessage) {
var m inMsg
if err := json.Unmarshal(raw, &m); err != nil {
s.protocolErrors.Add(1)
s.opt.Logf("bridge: undecodable message: %v", err)
return
}
switch m.T {
case "hello":
s.hello(m)
case "req":
s.request(m)
case "abort":
s.abort(m)
case "log":
if s.opt.OnPageLog != nil {
s.opt.OnPageLog(m.Level, m.Msg)
}
default:
s.protocolErrors.Add(1)
s.opt.Logf("bridge: unknown message type %q", m.T)
if m.ID != "" {
s.send(m.Gen, map[string]any{"t": "err", "id": m.ID, "gen": m.Gen, "code": "protocol", "message": "unknown message type " + m.T})
}
}
}
func (s *Session) hello(m inMsg) {
s.hellos.Add(1)
if m.V != ProtocolVersion {
s.protocolErrors.Add(1)
s.mu.Lock()
gen := s.gen
s.mu.Unlock()
// Reply on the current generation so the page sees the refusal.
s.sendAny(gen, map[string]any{"t": "ready", "nonce": m.Nonce, "error": fmt.Sprintf("unsupported bridge protocol %d (host speaks %d)", m.V, ProtocolVersion)})
return
}
s.mu.Lock()
if s.closed {
s.mu.Unlock()
return
}
s.gen++
gen := s.gen
for id, c := range s.calls {
if c.gen < gen {
c.cancel(ErrStale)
delete(s.calls, id)
}
}
s.mu.Unlock()
s.send(gen, map[string]any{"t": "ready", "v": ProtocolVersion, "gen": gen, "nonce": m.Nonce, "session": s.id})
if s.opt.OnHello != nil {
s.opt.OnHello(gen)
}
}
func (s *Session) request(m inMsg) {
s.requests.Add(1)
fail := func(code, msg string) {
s.send(m.Gen, map[string]any{"t": "err", "id": m.ID, "gen": m.Gen, "code": code, "message": msg})
}
if m.ID == "" {
s.protocolErrors.Add(1)
return
}
method := strings.ToUpper(m.Method)
if method == "" {
method = http.MethodGet
}
path, q, err := ParseLocalURL(m.URL)
if err != nil {
// A bad URL is a response (400), not a transport failure.
s.respond(m.Gen, m.ID, Text(http.StatusBadRequest, err.Error()))
return
}
var body []byte
if m.Body != nil {
if base64.StdEncoding.DecodedLen(len(*m.Body)) > s.opt.MaxBody+3 {
s.respond(m.Gen, m.ID, Text(http.StatusRequestEntityTooLarge, "request body too large"))
return
}
if body, err = base64.StdEncoding.DecodeString(*m.Body); err != nil {
s.protocolErrors.Add(1)
fail("protocol", "request body is not valid base64")
return
}
}
h := http.Header{}
for k, v := range m.Headers {
h.Set(k, v)
}
timeout := s.opt.MaxTimeout
if m.TimeoutMs > 0 && time.Duration(m.TimeoutMs)*time.Millisecond < timeout {
timeout = time.Duration(m.TimeoutMs) * time.Millisecond
}
s.mu.Lock()
switch {
case s.closed:
s.mu.Unlock()
s.droppedClosed.Add(1)
return
case m.Gen != s.gen:
s.mu.Unlock()
s.droppedStale.Add(1)
return
}
if _, dup := s.calls[m.ID]; dup {
s.mu.Unlock()
s.protocolErrors.Add(1)
fail("protocol", "duplicate request id")
return
}
ctx, cancel := context.WithCancelCause(context.Background())
ctx, cancelTimeout := context.WithTimeoutCause(ctx, timeout, ErrTimeout)
s.calls[m.ID] = &call{gen: m.Gen, cancel: cancel}
s.wg.Add(1)
s.mu.Unlock()
req := &Request{Method: method, URL: m.URL, Path: path, Query: q, Header: h, Body: body}
go func() {
defer s.wg.Done()
defer cancelTimeout()
resp, err := s.router.Serve(ctx, req)
if err == nil && resp.Stream != nil {
s.stream(ctx, cancel, m, req, resp)
return
}
s.mu.Lock()
_, live := s.calls[m.ID]
delete(s.calls, m.ID)
s.mu.Unlock()
cancel(nil)
if err != nil {
s.cancelled.Add(1)
code := "abort"
switch {
case errors.Is(err, ErrTimeout):
code = "timeout"
case errors.Is(err, ErrStale):
code = "stale"
case errors.Is(err, ErrClosed):
code = "closed"
}
// A call removed by abort/hello/Close already ended on the
// page side; only a host-side deadline still needs a reply.
if live {
fail(code, err.Error())
}
return
}
if !live {
s.droppedStale.Add(1)
return
}
s.completed.Add(1)
s.respond(m.Gen, m.ID, resp)
}()
}
func (s *Session) abort(m inMsg) {
s.mu.Lock()
c, ok := s.calls[m.ID]
if ok && c.gen == m.Gen {
delete(s.calls, m.ID)
}
s.mu.Unlock()
if ok && c.gen == m.Gen {
if m.Reason == "timeout" {
c.cancel(ErrTimeout)
} else {
c.cancel(ErrAborted)
}
}
}
func (s *Session) respond(gen uint64, id string, r *Response) {
hdr := map[string]string{}
for k, v := range r.Header {
hdr[strings.ToLower(k)] = strings.Join(v, ", ")
}
s.send(gen, map[string]any{
"t": "res", "id": id, "gen": gen, "status": r.Status, "statusText": http.StatusText(r.Status),
"headers": hdr, "body": base64.StdEncoding.EncodeToString(r.Body),
})
}
// send delivers msg to the page if gen is still the current generation and
// the session is open; otherwise the message is dropped and counted.
func (s *Session) send(gen uint64, msg map[string]any) { s.deliver(gen, msg, true) }
// sendAny delivers without a generation check (protocol refusal).
func (s *Session) sendAny(gen uint64, msg map[string]any) { s.deliver(gen, msg, false) }
func (s *Session) deliver(gen uint64, msg map[string]any, checkGen bool) {
b, err := json.Marshal(msg)
if err != nil {
s.opt.Logf("bridge: marshal: %v", err)
return
}
// json.Marshal escapes <, >, &, U+2028 and U+2029, so b is a safe JS
// expression.
js := "window.__yetano_recv&&window.__yetano_recv(" + string(b) + ")"
ok := func() bool {
if s.closed {
s.droppedClosed.Add(1)
return false
}
if checkGen && gen != s.gen {
s.droppedStale.Add(1)
return false
}
return true
}
s.mu.Lock()
d := s.d
if !ok() || d == nil {
s.mu.Unlock()
return
}
s.mu.Unlock()
d.Dispatch(func() {
// Re-check on the UI thread: a reload or Close may have happened
// while this closure was queued.
s.mu.Lock()
live := ok()
s.mu.Unlock()
if live {
d.Eval(js)
}
})
}
// stream delivers a Stream response as res(stream:true), chunk..., end.
// The call stays registered (abortable, generation-bound) until the end.
func (s *Session) stream(ctx context.Context, cancel context.CancelCauseFunc, m inMsg, req *Request, resp *Response) {
hdr := map[string]string{}
for k, v := range resp.Header {
hdr[strings.ToLower(k)] = strings.Join(v, ", ")
}
s.send(m.Gen, map[string]any{"t": "res", "id": m.ID, "gen": m.Gen, "status": resp.Status,
"statusText": http.StatusText(resp.Status), "headers": hdr, "stream": true})
serr := resp.Stream(ctx, &chunkWriter{s: s, ctx: ctx, gen: m.Gen, id: m.ID})
cerr := ctx.Err()
s.mu.Lock()
_, live := s.calls[m.ID]
delete(s.calls, m.ID)
s.mu.Unlock()
cancel(nil)
switch {
case cerr != nil:
s.cancelled.Add(1)
if live { // host-side deadline; page-side ends are already settled
code := "abort"
if errors.Is(context.Cause(ctx), ErrTimeout) {
code = "timeout"
}
s.send(m.Gen, map[string]any{"t": "err", "id": m.ID, "gen": m.Gen, "code": code, "message": context.Cause(ctx).Error()})
}
case serr != nil:
s.send(m.Gen, map[string]any{"t": "err", "id": m.ID, "gen": m.Gen, "code": "stream", "message": fmt.Sprintf("%s %s: %v", req.Method, req.Path, serr)})
default:
s.completed.Add(1)
s.send(m.Gen, map[string]any{"t": "end", "id": m.ID, "gen": m.Gen})
}
}
// chunkWriter sends every Write as chunk message(s) of at most 192 KiB.
type chunkWriter struct {
s *Session
ctx context.Context
gen uint64
id string
}
func (w *chunkWriter) Write(p []byte) (int, error) {
const max = 192 << 10
for off := 0; off < len(p); off += max {
if err := w.ctx.Err(); err != nil {
return off, context.Cause(w.ctx)
}
end := min(off+max, len(p))
w.s.send(w.gen, map[string]any{"t": "chunk", "id": w.id, "gen": w.gen, "data": base64.StdEncoding.EncodeToString(p[off:end])})
}
return len(p), nil
}
// Close blocks new calls, invalidates the generation, cancels running
// handlers and waits (bounded) for them. It never needs the UI thread, so it
// can be called after the native loop ended and before the window is
// destroyed. Close is idempotent.
func (s *Session) Close() error {
s.mu.Lock()
if s.closed {
s.mu.Unlock()
return nil
}
s.closed = true
for id, c := range s.calls {
c.cancel(ErrClosed)
delete(s.calls, id)
}
s.mu.Unlock()
done := make(chan struct{})
go func() { s.wg.Wait(); close(done) }()
select {
case <-done:
return nil
case <-time.After(s.opt.CloseWait):
return fmt.Errorf("bridge: handlers still running %s after close (they ignore their context)", s.opt.CloseWait)
}
}
+358
View File
@@ -0,0 +1,358 @@
package bridge
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"testing"
"testing/fstest"
"time"
"yetano.dev/yetano/core/gui/assets"
)
// fakeUI runs dispatched functions serially on one goroutine (like a UI
// thread) and decodes every Eval into a message.
type fakeUI struct {
q chan func()
msgs chan map[string]any
once sync.Once
}
func newFakeUI() *fakeUI {
u := &fakeUI{q: make(chan func(), 256), msgs: make(chan map[string]any, 256)}
go func() {
for f := range u.q {
f()
}
}()
return u
}
func (u *fakeUI) Dispatch(f func()) { u.q <- f }
func (u *fakeUI) Eval(js string) {
const p = "window.__yetano_recv&&window.__yetano_recv("
var m map[string]any
if err := json.Unmarshal([]byte(strings.TrimSuffix(strings.TrimPrefix(js, p), ")")), &m); err != nil {
panic(err)
}
u.msgs <- m
}
func (u *fakeUI) next(t *testing.T) map[string]any {
t.Helper()
select {
case m := <-u.msgs:
return m
case <-time.After(3 * time.Second):
t.Fatal("no message")
return nil
}
}
func (u *fakeUI) none(t *testing.T, d time.Duration) {
t.Helper()
select {
case m := <-u.msgs:
t.Fatalf("unexpected message %v", m)
case <-time.After(d):
}
}
type harness struct {
s *Session
ui *fakeUI
started chan string
causes chan error
}
func newHarness(t *testing.T) *harness {
res, _ := assets.NewResolver(assets.NewFSSource("t", fstest.MapFS{"a.wasm": {Data: []byte("\x00asm\x01\x00\x00\x00")}}))
r := NewRouter(res)
h := &harness{ui: newFakeUI(), started: make(chan string, 16), causes: make(chan error, 16)}
must := func(err error) {
if err != nil {
t.Fatal(err)
}
}
must(r.Handle("POST", "/rpc/add", func(_ context.Context, req *Request) (*Response, error) {
var in struct{ A, B int }
json.Unmarshal(req.Body, &in)
return JSONBytes(200, []byte(fmt.Sprintf(`{"result":%d}`, in.A+in.B))), nil
}))
must(r.Handle("POST", "/rpc/block", func(ctx context.Context, req *Request) (*Response, error) {
h.started <- string(req.Body)
<-ctx.Done()
h.causes <- context.Cause(ctx)
return nil, ctx.Err()
}))
must(r.Handle("GET", "/rpc/panic", func(context.Context, *Request) (*Response, error) { panic("boom") }))
if err := r.Handle("POST", "/rpc/add", nil); err == nil {
t.Fatal("nil/duplicate handler accepted")
}
if err := r.Handle("POST", "/rpc/add", func(context.Context, *Request) (*Response, error) { return nil, nil }); err == nil {
t.Fatal("duplicate route accepted")
}
h.s = NewSession(r, Options{CloseWait: time.Second})
if err := r.Handle("GET", "/late", func(context.Context, *Request) (*Response, error) { return nil, nil }); err == nil {
t.Fatal("route after session start accepted")
}
h.s.Attach(h.ui)
t.Cleanup(func() { h.s.Close() })
return h
}
func (h *harness) post(v any) {
b, _ := json.Marshal(v)
h.s.Post(b)
}
func (h *harness) hello(t *testing.T) uint64 {
h.post(map[string]any{"t": "hello", "v": ProtocolVersion, "nonce": "n"})
m := h.ui.next(t)
if m["t"] != "ready" || m["nonce"] != "n" {
t.Fatalf("ready: %v", m)
}
return uint64(m["gen"].(float64))
}
func (h *harness) req(gen uint64, id, method, url, body string) {
var b *string
if body != "" {
e := base64.StdEncoding.EncodeToString([]byte(body))
b = &e
}
h.post(map[string]any{"t": "req", "id": id, "gen": gen, "method": method, "url": url, "body": b})
}
func body(t *testing.T, m map[string]any) string {
b, err := base64.StdEncoding.DecodeString(m["body"].(string))
if err != nil {
t.Fatal(err)
}
return string(b)
}
func TestRoundtripAndResponses(t *testing.T) {
h := newHarness(t)
g := h.hello(t)
h.req(g, "1", "POST", "/rpc/add", `{"a":3,"b":4}`)
m := h.ui.next(t)
if m["t"] != "res" || m["id"] != "1" || m["status"].(float64) != 200 || body(t, m) != `{"result":7}` {
t.Fatalf("%v", m)
}
cases := map[string]float64{"/rpc/nope": 404, "/rpc/panic": 500, "/assets/../x": 400, "/assets/a.wasm": 200, "assets:a.wasm": 200, "//evil/x": 400, "/assets/missing": 404}
i := 10
for u, want := range cases {
i++
h.req(g, fmt.Sprint(i), "GET", u, "")
m := h.ui.next(t)
if m["status"].(float64) != want {
t.Errorf("%s: %v", u, m["status"])
}
if u == "/assets/a.wasm" && m["headers"].(map[string]any)["content-type"] != "application/wasm" {
t.Errorf("wasm mime: %v", m["headers"])
}
}
h.req(g, "h", "HEAD", "/assets/a.wasm", "")
if m := h.ui.next(t); body(t, m) != "" || m["headers"].(map[string]any)["content-length"] != "8" {
t.Errorf("HEAD: %v", m)
}
h.req(g, "m", "PUT", "/rpc/add", "")
if m := h.ui.next(t); m["status"].(float64) != 405 {
t.Errorf("405: %v", m)
}
}
func TestProtocolVersionMismatch(t *testing.T) {
h := newHarness(t)
h.post(map[string]any{"t": "hello", "v": 99, "nonce": "x"})
m := h.ui.next(t)
if m["t"] != "ready" || !strings.Contains(fmt.Sprint(m["error"]), "unsupported bridge protocol 99") {
t.Fatalf("%v", m)
}
if h.s.Stats().Generation != 0 {
t.Error("generation advanced on refused hello")
}
}
func TestAbortReachesHandler(t *testing.T) {
h := newHarness(t)
g := h.hello(t)
h.req(g, "1", "POST", "/rpc/block", "x")
<-h.started
h.post(map[string]any{"t": "abort", "id": "1", "gen": g})
if c := <-h.causes; !errors.Is(c, ErrAborted) {
t.Fatalf("cause %v", c)
}
h.ui.none(t, 100*time.Millisecond) // the page already settled the call
}
func TestStaleGenerationCancelledAndDropped(t *testing.T) {
h := newHarness(t)
g1 := h.hello(t)
h.req(g1, "1", "POST", "/rpc/block", "old")
<-h.started
g2 := h.hello(t) // reload
if g2 != g1+1 {
t.Fatalf("gen %d -> %d", g1, g2)
}
if c := <-h.causes; !errors.Is(c, ErrStale) {
t.Fatalf("cause %v", c)
}
h.ui.none(t, 100*time.Millisecond)
// A request still tagged with the old generation is dropped.
h.req(g1, "2", "POST", "/rpc/add", `{"a":1,"b":1}`)
h.ui.none(t, 100*time.Millisecond)
if h.s.Stats().DroppedStale == 0 {
t.Error("stale request not counted")
}
}
func TestCloseCancelsAndBlocksDelivery(t *testing.T) {
h := newHarness(t)
g := h.hello(t)
h.req(g, "1", "POST", "/rpc/block", "x")
<-h.started
if err := h.s.Close(); err != nil {
t.Fatal(err)
}
if c := <-h.causes; !errors.Is(c, ErrClosed) {
t.Fatalf("cause %v", c)
}
if err := h.s.Close(); err != nil {
t.Fatal("second close", err)
}
h.req(g, "2", "POST", "/rpc/add", `{"a":1,"b":1}`)
h.ui.none(t, 100*time.Millisecond)
if st := h.s.Stats(); st.Pending != 0 || st.DroppedClosed == 0 {
t.Errorf("%+v", st)
}
}
func TestDuplicateIDAndBadMessages(t *testing.T) {
h := newHarness(t)
g := h.hello(t)
h.req(g, "1", "POST", "/rpc/block", "x")
<-h.started
h.req(g, "1", "POST", "/rpc/add", `{}`)
if m := h.ui.next(t); m["code"] != "protocol" {
t.Fatalf("%v", m)
}
h.s.Post(json.RawMessage(`"string"`))
h.s.Post(json.RawMessage(`{"t":"bogus","id":"z","gen":1}`))
if m := h.ui.next(t); m["code"] != "protocol" {
t.Fatalf("%v", m)
}
if h.s.Stats().ProtocolErrors < 3 {
t.Errorf("%+v", h.s.Stats())
}
}
func TestHostTimeout(t *testing.T) {
res, _ := assets.NewResolver(assets.NewFSSource("t", fstest.MapFS{}))
r := NewRouter(res)
r.Handle("GET", "/slow", func(ctx context.Context, _ *Request) (*Response, error) { <-ctx.Done(); return nil, ctx.Err() })
s := NewSession(r, Options{MaxTimeout: 50 * time.Millisecond})
ui := newFakeUI()
s.Attach(ui)
defer s.Close()
s.Post(json.RawMessage(`{"t":"hello","v":1,"nonce":"n"}`))
ui.next(t)
s.Post(json.RawMessage(`{"t":"req","id":"1","gen":1,"method":"GET","url":"/slow"}`))
if m := ui.next(t); m["t"] != "err" || m["code"] != "timeout" {
t.Fatalf("%v", m)
}
}
func TestParseLocalURL(t *testing.T) {
p, q, err := ParseLocalURL("assets:img/a.png?x=1#f")
if err != nil || p != "/assets/img/a.png" || q.Get("x") != "1" {
t.Fatal(p, q, err)
}
if p, _, _ := ParseLocalURL("/assets/%252e"); p != "/assets/%2e" {
t.Errorf("decoded more than once: %q", p)
}
for _, bad := range []string{"https://x/y", "//x/y", "rel/path", "/a%zz"} {
if _, _, err := ParseLocalURL(bad); err == nil {
t.Errorf("%q accepted", bad)
}
}
}
func TestInitScript(t *testing.T) {
js := InitScript(PageConfig{Selftest: true})
if !strings.HasPrefix(js, `window.__yetano_config={"external":"reject"`) || !strings.Contains(js, "__yetano_post") {
t.Fatal(js[:120])
}
_ = http.StatusOK
}
func TestStreamChunksAndAbort(t *testing.T) {
res, _ := assets.NewResolver(assets.NewFSSource("t", fstest.MapFS{}))
r := NewRouter(res)
causes := make(chan error, 1)
r.Handle("GET", "/s", func(context.Context, *Request) (*Response, error) {
return &Response{Status: 200, Stream: func(ctx context.Context, w io.Writer) error {
for i := 0; ; i++ {
if _, err := fmt.Fprintf(w, "c%d", i); err != nil {
causes <- err
return err
}
if i == 2 {
// after three chunks wait for the page to abort
<-ctx.Done()
causes <- context.Cause(ctx)
return ctx.Err()
}
}
}}, nil
})
r.Handle("GET", "/done", func(context.Context, *Request) (*Response, error) {
return &Response{Status: 201, Stream: func(_ context.Context, w io.Writer) error {
w.Write(make([]byte, 400<<10)) // split into 192 KiB chunks
return nil
}}, nil
})
s := NewSession(r, Options{})
ui := newFakeUI()
s.Attach(ui)
defer s.Close()
s.Post(json.RawMessage(`{"t":"hello","v":1,"nonce":"n"}`))
ui.next(t)
s.Post(json.RawMessage(`{"t":"req","id":"1","gen":1,"method":"GET","url":"/s"}`))
if m := ui.next(t); m["t"] != "res" || m["stream"] != true {
t.Fatalf("head: %v", m)
}
for i := 0; i < 3; i++ {
if m := ui.next(t); m["t"] != "chunk" {
t.Fatalf("chunk %d: %v", i, m)
}
}
s.Post(json.RawMessage(`{"t":"abort","id":"1","gen":1}`))
if c := <-causes; !errors.Is(c, ErrAborted) {
t.Fatalf("cause %v", c)
}
ui.none(t, 100*time.Millisecond) // page already ended the stream: no end/err
s.Post(json.RawMessage(`{"t":"req","id":"2","gen":1,"method":"GET","url":"/done"}`))
if m := ui.next(t); m["status"].(float64) != 201 {
t.Fatalf("%v", m)
}
total := 0
for {
m := ui.next(t)
if m["t"] == "end" {
break
}
b, _ := base64.StdEncoding.DecodeString(m["data"].(string))
total += len(b)
}
if total != 400<<10 {
t.Fatalf("streamed %d bytes", total)
}
}