Files
ai/controllers/zap_forward_test.go
zeekay 3d4d01d770 feat(web): wire the ai runtime onto the native router, drop beego routing
Replaces beego's ControllerRegister, filter chain and context with the native
web package end to end. The controllers, filters and routes are retyped from
beego.Context/beego.Controller to their web equivalents (web.Context mirrors
beego's API, so the swap is mechanical), and the 307 explicit routes register
on a shared routers.App (web.Router). The dead NSInclude namespace is dropped:
without a generated commentsRouter it registered nothing.

- controllers/base.go embeds web.Controller; the 4 streaming/util controllers,
  the 17 filters, util/cookie.go and object/record.go take *web.Context.
- routers.InstallFilters inserts the 14 BeforeRouter + 2 AfterExec filters on
  App in the same order the standalone used; bootstrap and the route tests
  share it.
- The session provider binds through App.UseSessions (its Store matches
  web.Store); Bootstrap publishes App as the request handler instead of
  beego.BeeApp.Handlers.
- web gains the Controller compatibility surface the handlers use: EnableRender,
  GetFile, Context.SetCookie/Output.Cookie; RunMode defaults to prod (compact
  ServeJSON), matching the runtime default. The /swagger static (beego
  SetStaticPath) is dropped — the edge serves statics.

Verified on SQLite (UseMemoryDB): /v1/cloud/* rewrites and dispatches, the
/v1/iam/* alias is selective (in-set dispatches, out-of-set 404s), an
unauthenticated gated /v1/cloud/get-providers is denied 401/403 before
dispatch, and the real filter chain short-circuits on auth-reject in order.
go build ./... and the web/routers/controllers/route tests are green; the
beego module stays until the session and lifecycle cuts.
2026-07-17 21:56:49 -07:00

130 lines
4.3 KiB
Go

// Copyright 2023-2026 Hanzo AI Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"context"
"io"
"net"
"net/http"
"strconv"
"strings"
"testing"
"time"
web "github.com/hanzoai/ai/web"
zaplib "github.com/luxfi/zap"
"github.com/luxfi/zap/forward"
)
// healthHandler builds the same fully-wrapped surface ai bridges in
// production — a *beego.ControllerRegister (which is an http.Handler) — but
// scoped to the one always-present, auth-exempt route used here: GET
// /v1/health → ApiController.Health → 200 + {"status":"ok",...}. Using the
// real ControllerRegister + real controller method proves the bridge drives
// beego routing and controller dispatch over ZAP, without booting ai's full
// DB/adapter/filter stack (the production handle is the same type).
func healthHandler() http.Handler {
r := web.NewRouter()
r.Router("/v1/health", &ApiController{}, "GET:Health")
return r
}
// TestForwardBridgeServesBeegoHandler stands up two live ZAP nodes, registers
// the canonical HTTP-over-ZAP terminal (forward.Serve) on the backend with a
// real beego handler, and asserts GET /v1/health round-trips through the
// bridge with status 200 and a JSON body. This exercises exactly what
// InitForwardBridge wires in cmd/aid/main.go.
func TestForwardBridgeServesBeegoHandler(t *testing.T) {
gwPort := freePort(t)
bePort := freePort(t)
gw := zaplib.NewNode(zaplib.NodeConfig{NodeID: "gateway-test", Port: gwPort, NoDiscovery: true})
be := zaplib.NewNode(zaplib.NodeConfig{NodeID: "ai-test", Port: bePort, NoDiscovery: true})
if err := gw.Start(); err != nil {
t.Fatalf("gateway node start: %v", err)
}
defer gw.Stop()
if err := be.Start(); err != nil {
t.Fatalf("backend node start: %v", err)
}
defer be.Stop()
// Register the Forward terminal on the backend node — the same call
// InitForwardBridge makes, with the same kind of beego http.Handler.
forward.Serve(be, healthHandler())
// Gateway dials the backend, then waits until the peer is visible.
if err := gw.ConnectDirect("127.0.0.1:" + strconv.Itoa(bePort)); err != nil {
t.Fatalf("gateway dial backend: %v", err)
}
waitForPeer(t, gw, "ai-test")
fwd := &forward.Forwarder{Node: gw, Peer: "ai-test"}
req, _ := http.NewRequest(http.MethodGet, "http://ai-test/v1/health", nil)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
resp, err := fwd.RoundTrip(req.WithContext(ctx))
if err != nil {
t.Fatalf("RoundTrip /v1/health: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("status: got %d want %d", resp.StatusCode, http.StatusOK)
}
body, _ := io.ReadAll(resp.Body)
// ApiController.Health -> ResponseOk -> {"status":"ok","msg":"",...}.
if !strings.Contains(string(body), `"status":"ok"`) {
t.Fatalf("body did not carry the health payload through the bridge: %q", body)
}
}
// TestInitForwardBridgeNoNode asserts the wiring is a safe no-op when ZAP is
// off (object.GetZapNode() == nil) — InitForwardBridge must not panic and ai's
// HTTP behavior is unchanged. ZAP_ENABLED is unset in the test environment, so
// the node is never created.
func TestInitForwardBridgeNoNode(t *testing.T) {
// healthHandler() is non-nil; the guard must short-circuit on the nil node.
InitForwardBridge(healthHandler())
}
func freePort(t *testing.T) int {
t.Helper()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("reserve free port: %v", err)
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port
}
func waitForPeer(t *testing.T, n *zaplib.Node, peer string) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
for _, p := range n.Peers() {
if p == peer {
return
}
}
time.Sleep(20 * time.Millisecond)
}
t.Fatalf("peer %q not connected within deadline (peers=%v)", peer, n.Peers())
}