Files
core/gui/bridge/router.go
T
terminarandClaude Opus 5.5 8c63d42a27 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>
2026-10-23 14:47:26 +02:00

266 lines
8.0 KiB
Go

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
}