// 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) } }