Files
zip/runtime/runner_test.go
zeekayandGitHub 8d4e50c665 feat(runtime): embed goja + esbuild; ZAP-over-HTTP transport (#9)
* feat(runtime): embed goja + esbuild; add ZAP-over-HTTP transport

Establish zip as the canonical Hanzo Go web framework with embedded
in-process JS execution and a native ZAP RPC HTTP transport. One Go
binary mounts native handlers, legacy TS/JS handlers, WebSocket, and
the ZAP RPC plane — no separate runtime service, no inter-service RPC,
no container-per-service.

zip/runtime/ (new):
- jsvm.go    NewJSRuntime / Eval / RegisterHostFn / LoadModule, backed
             by a pool of *goja.Runtime (pure Go, no CGO). Pool pattern
             lifted from hanzoai/base/plugins/gojavm, slimmed to run +
             forEach so late host-fn / module registration reaches warm
             VMs.
- pool.go    fixed-size goja VM pool; saturated calls fall back to a
             fully-provisioned one-off VM.
- require.go CommonJS-style require(): per-VM module sources + memoized
             exports in a Go-side side-table (never visible to JS).
- esbuild.go TranspileToES5: TS/modern-JS -> goja-ready JS via esbuild's
             pure-Go API (ES2015 target, CommonJS format).
- handler.go JSHandler / JSModule: mount an Express-shaped (req, res) JS
             function as a fiber.Handler; req mirrors method/path/query/
             headers/body, res mirrors status/set/json/send.
- json.go    encode/decode through internal/jsonenc — one wire format.

zip/zaprpc/ (new on existing Registry seam):
- envelope.go canonical ZAP RPC frame (service/method/payload) over the
              zap-proto/go wire codec.
- http.go     HTTPHandler(reg): serves the ZAP RPC plane over HTTP POST;
              binary envelope canonical, X-ZAP-* headers are a hint only.

examples/express-in-zip/ (new): legacy app.ts -> real esbuild -> real
goja -> real Fiber -> real HTTP, with an integration test proving
GET /legacy/foo and POST /legacy/bar body echo.

README: embedded-JS migration path + single-binary (HIP-0106) sections.

go build ./... and go test ./... (incl. -race) pass.

* feat(runtime): ctx-aware Eval + multi-file BundleToES2015

Two consumer-integration follow-ups so callers (base's gojavm) stop
reaching past the runtime abstraction.

EvalContext(ctx, src): interrupt a running goja VM when ctx fires.
A watcher goroutine calls vm.Interrupt(ctx.Err()) on ctx.Done(); the
resulting *goja.InterruptedError is unwrapped back to ctx.Err(). The
watcher is joined and ClearInterrupt() is called before the VM is
returned to the pool, so a borrowed VM is never left interrupted.
Eval routes through EvalContext(context.Background()). InvokeFunc(ctx,
fnName, args...) calls a named global JS function under the same
cancellation discipline. This lets base drop the goroutine+timeout race
around Invoke.

BundleToES2015(entry, files, opts): transpile + bundle a multi-file
TS/JS tree from an in-memory files map using esbuild's pure-Go Build
API with an onResolve/onLoad plugin serving a virtual namespace — no
real FS access, no CGO. Relative imports resolve against the importer's
dir; opts.External keeps bare specifiers as require()/import calls for
goja to resolve at runtime. This replaces consumers importing esbuild's
api package directly to bundle.

Tests (go test -race clean):
- EvalContext(50ms, while(true){}) returns DeadlineExceeded in ~50ms
- successful eval returns the value; VM reusable afterwards
- two-file CommonJS bundle runs in goja, entry.run() === 42
- external dep stays require("external") and resolves via host module

* feat(runtime): unified multi-language Runner over the extruntime SPI

Add Runner — a registry of language → Engine that executes arbitrary-
language source in goroutine-scoped, context.Context-bound tasks. Each
Run spawns a worker (engine.Eval) and a watcher (ctx.Done() → engine
interrupt), joining both before return so a borrowed VM is never handed
back to its pool while still interrupted. This generalizes the settled
JSRuntime.EvalContext cancellation contract (one worker, one watcher,
joined, engine-specific interrupt) across every backend a host registers.

zip ships exactly one in-tree engine: the pure-Go goja engine, surfaced
via (*JSRuntime).Engine() and registered as "js". It self-manages ctx
inside EvalContext (per-call interrupt on the exact borrowed VM), so the
Runner's watcher is a benign no-op for it. base's backends (pyvm, v8vm,
wasmvm, starkvm) plug in through the same Engine seam via thin extruntime
adapters at app startup — the registry is the seam, not an import edge.
zip never imports base; the dependency direction stays base → zip.

Engine is the zip-side projection of base's extruntime backends: any
value implementing Eval(ctx, src, args) satisfies it. Optional
Interruptible lets the watcher abort a runaway eval out-of-band.

Wire the unified runner into examples/express-in-zip: POST /runtime/:lang
reads the body as source, dispatches to the engine for :lang, returns
{result} or 404 {error:"unknown language"}.

Tests (go test -race, all green):
  - JS happy path: Run(ctx, "js", "1+2") → int64(3)
  - JS function call: define + invoke in one eval
  - JS ctx deadline: while(true){} interrupted, DeadlineExceeded, ~50ms
  - unknown language: ErrUnknownLanguage sentinel, no panic
  - concurrent: 100 goroutines, registry RWMutex + per-call VM isolation
  - example: POST /runtime/js "40+2" → {"result":42}; cobol → 404

No cgo. No base import. README documents the Runner + SPI registration.
2026-06-16 16:05:27 -07:00

140 lines
3.8 KiB
Go

package runtime
import (
"context"
"errors"
"fmt"
"math/rand"
"sync"
"testing"
"time"
)
// newJSRunner builds a Runner with zip's real goja engine registered as
// "js". No stubs: this is the same *JSRuntime base/gojavm wraps.
func newJSRunner(t *testing.T) Runner {
t.Helper()
rt, err := NewJSRuntime(JSOptions{PoolSize: 8})
if err != nil {
t.Fatalf("NewJSRuntime: %v", err)
}
r := NewRunner()
if err := r.Register("js", rt.Engine()); err != nil {
t.Fatalf("Register js: %v", err)
}
return r
}
// TestRunnerJSHappyPath: real goja, real arithmetic, real Export() result.
func TestRunnerJSHappyPath(t *testing.T) {
r := newJSRunner(t)
got, err := r.Run(context.Background(), "js", []byte("1+2"))
if err != nil {
t.Fatalf("Run: %v", err)
}
if got != int64(3) {
t.Fatalf("1+2 = %#v (%T), want int64(3)", got, got)
}
}
// TestRunnerJSFunctionCall defines a function and returns the result of
// calling it via a top-level expression — proving a defined function is
// reachable and invocable in the same eval.
func TestRunnerJSFunctionCall(t *testing.T) {
r := newJSRunner(t)
got, err := r.Run(context.Background(), "js",
[]byte("function add(a,b){return a+b}; add(40,2)"))
if err != nil {
t.Fatalf("Run: %v", err)
}
if got != int64(42) {
t.Fatalf("add(40,2) = %#v (%T), want int64(42)", got, got)
}
// And capture the function value itself, then confirm it round-trips
// as a callable (Export of a goja function is a Go func wrapper).
fnVal, err := r.Run(context.Background(), "js",
[]byte("function add(a,b){return a+b}; add"))
if err != nil {
t.Fatalf("Run capture fn: %v", err)
}
if fnVal == nil {
t.Fatalf("captured function is nil")
}
}
// TestRunnerJSDeadline: an infinite loop must be interrupted by ctx
// deadline. Asserts the error is context.DeadlineExceeded and the wall
// time is bounded (interrupt actually fired, not a hung worker).
func TestRunnerJSDeadline(t *testing.T) {
r := newJSRunner(t)
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
start := time.Now()
_, err := r.Run(ctx, "js", []byte("while(true){}"))
elapsed := time.Since(start)
t.Logf("deadline test elapsed: %v", elapsed)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v, want context.DeadlineExceeded", err)
}
if elapsed > 200*time.Millisecond {
t.Fatalf("elapsed %v > 200ms: interrupt did not fire promptly", elapsed)
}
}
// TestRunnerUnknownLanguage: dispatch to an unregistered language returns
// the typed sentinel, not a panic.
func TestRunnerUnknownLanguage(t *testing.T) {
r := newJSRunner(t)
_, err := r.Run(context.Background(), "cobol", []byte("DISPLAY 'HI'."))
if !errors.Is(err, ErrUnknownLanguage) {
t.Fatalf("err = %v, want ErrUnknownLanguage", err)
}
}
// TestRunnerConcurrent: 100 goroutines each evaluate a distinct random
// expression a+b and assert the result. Run under -race this proves the
// registry RWMutex and the per-call VM isolation are sound.
func TestRunnerConcurrent(t *testing.T) {
r := newJSRunner(t)
const n = 100
var wg sync.WaitGroup
errs := make(chan error, n)
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
defer wg.Done()
a := rand.Intn(10000)
b := rand.Intn(10000)
src := fmt.Sprintf("%d+%d", a, b)
got, err := r.Run(context.Background(), "js", []byte(src))
if err != nil {
errs <- fmt.Errorf("%s: %w", src, err)
return
}
if got != int64(a+b) {
errs <- fmt.Errorf("%s = %#v, want %d", src, got, a+b)
}
}()
}
wg.Wait()
close(errs)
for err := range errs {
t.Error(err)
}
}
// TestRunnerLanguages: registry reports registered languages, sorted.
func TestRunnerLanguages(t *testing.T) {
r := newJSRunner(t)
langs := r.Languages()
if len(langs) != 1 || langs[0] != "js" {
t.Fatalf("Languages() = %v, want [js]", langs)
}
}