mirror of
https://github.com/hanzoai/zip.git
synced 2026-10-30 20:11:40 +00:00
* 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.
216 lines
6.0 KiB
Go
216 lines
6.0 KiB
Go
// handler.go bridges a goja-loaded JS function into Fiber. It returns
|
|
// fiber.Handler (not zip.Handler) on purpose: the zip root package
|
|
// imports this package, so depending back on zip would be an import
|
|
// cycle. fiber.Handler mounts cleanly anywhere — app.Fiber().Get(...)
|
|
// or any *fiber.App — and is the natural seam for legacy Express-shaped
|
|
// handlers running inside the embedded VM.
|
|
//
|
|
// The req/res objects handed to JS mirror the Express shape so existing
|
|
// `function (req, res) { res.json(...) }` handlers run unmodified:
|
|
//
|
|
// req.method req.path req.query req.headers req.body
|
|
// res.status(n) res.set(k,v) res.json(v) res.send(v)
|
|
package runtime
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/dop251/goja"
|
|
"github.com/gofiber/fiber/v3"
|
|
)
|
|
|
|
// jsResponse captures what the JS handler wrote, so we can replay it onto
|
|
// the Fiber Ctx after the VM call returns. goja runs single-threaded per
|
|
// borrowed VM, so a fresh jsResponse per request is race-free.
|
|
type jsResponse struct {
|
|
status int
|
|
headers map[string]string
|
|
body []byte
|
|
isJSON bool
|
|
written bool
|
|
}
|
|
|
|
// JSHandler returns a fiber.Handler that invokes the global JS function
|
|
// named fnName (defined in the runtime via Eval / LoadModule) with an
|
|
// Express-shaped (req, res) pair. State written through res is propagated
|
|
// back onto the Fiber Ctx after the call.
|
|
func JSHandler(rt *JSRuntime, fnName string) fiber.Handler {
|
|
return func(fc fiber.Ctx) error {
|
|
return rt.withVM(func(vm *goja.Runtime) error {
|
|
fnVal := vm.Get(fnName)
|
|
fn, ok := goja.AssertFunction(fnVal)
|
|
if !ok {
|
|
return fmt.Errorf("zip/runtime: %q is not a callable JS function", fnName)
|
|
}
|
|
return invokeJS(fc, vm, fn)
|
|
})
|
|
}
|
|
}
|
|
|
|
// JSModule loads a CommonJS module whose `module.exports` is the handler
|
|
// function (Express shape) and returns a fiber.Handler for it. modulePath
|
|
// is the name the module was registered under via LoadModule.
|
|
func JSModule(rt *JSRuntime, modulePath string) (fiber.Handler, error) {
|
|
// Resolve once up front so a missing/invalid module fails at mount
|
|
// time, not on the first request.
|
|
var resolved goja.Callable
|
|
err := rt.withVM(func(vm *goja.Runtime) error {
|
|
exports, err := requireModule(vm, modulePath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, ok := goja.AssertFunction(exports); !ok {
|
|
return fmt.Errorf("zip/runtime: module %q exports is not a function", modulePath)
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
_ = resolved // resolution is per-VM; re-resolved inside the handler.
|
|
|
|
return func(fc fiber.Ctx) error {
|
|
return rt.withVM(func(vm *goja.Runtime) error {
|
|
exports, err := requireModule(vm, modulePath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
fn, ok := goja.AssertFunction(exports)
|
|
if !ok {
|
|
return fmt.Errorf("zip/runtime: module %q exports is not a function", modulePath)
|
|
}
|
|
return invokeJS(fc, vm, fn)
|
|
})
|
|
}, nil
|
|
}
|
|
|
|
// invokeJS builds the req/res objects, calls fn(req, res), then replays
|
|
// the captured response onto the Fiber Ctx.
|
|
func invokeJS(fc fiber.Ctx, vm *goja.Runtime, fn goja.Callable) error {
|
|
resp := &jsResponse{status: 200, headers: map[string]string{}}
|
|
|
|
req := buildReq(vm, fc)
|
|
res := buildRes(vm, resp)
|
|
|
|
if _, err := fn(goja.Undefined(), req, res); err != nil {
|
|
return err
|
|
}
|
|
return replay(fc, resp)
|
|
}
|
|
|
|
// buildReq materialises the Express-shaped req object from the Fiber Ctx.
|
|
func buildReq(vm *goja.Runtime, fc fiber.Ctx) *goja.Object {
|
|
req := vm.NewObject()
|
|
_ = req.Set("method", fc.Method())
|
|
_ = req.Set("path", fc.Path())
|
|
_ = req.Set("url", fc.OriginalURL())
|
|
|
|
// query: flat map of first values.
|
|
query := vm.NewObject()
|
|
for k, v := range fc.Queries() {
|
|
_ = query.Set(k, v)
|
|
}
|
|
_ = req.Set("query", query)
|
|
|
|
// headers: lowercased keys, Express convention.
|
|
headers := vm.NewObject()
|
|
for k, v := range fc.GetReqHeaders() {
|
|
if len(v) > 0 {
|
|
_ = headers.Set(k, v[0])
|
|
}
|
|
}
|
|
_ = req.Set("headers", headers)
|
|
|
|
// body: parsed JSON when Content-Type is JSON and the body is
|
|
// non-empty, otherwise null. Matches Express + body-parser.
|
|
body := fc.Body()
|
|
if len(body) > 0 && isJSONContentType(fc.Get(fiber.HeaderContentType)) {
|
|
var parsed any
|
|
if err := jsonUnmarshal(body, &parsed); err == nil {
|
|
_ = req.Set("body", vm.ToValue(parsed))
|
|
} else {
|
|
_ = req.Set("body", goja.Null())
|
|
}
|
|
} else {
|
|
_ = req.Set("body", goja.Null())
|
|
}
|
|
return req
|
|
}
|
|
|
|
// buildRes materialises the Express-shaped res object backed by resp.
|
|
func buildRes(vm *goja.Runtime, resp *jsResponse) *goja.Object {
|
|
res := vm.NewObject()
|
|
|
|
// res.status(n) -> res (chainable)
|
|
_ = res.Set("status", func(call goja.FunctionCall) goja.Value {
|
|
if len(call.Arguments) > 0 {
|
|
resp.status = int(call.Argument(0).ToInteger())
|
|
}
|
|
return res
|
|
})
|
|
|
|
// res.set(k, v) -> res (chainable)
|
|
_ = res.Set("set", func(call goja.FunctionCall) goja.Value {
|
|
if len(call.Arguments) >= 2 {
|
|
resp.headers[call.Argument(0).String()] = call.Argument(1).String()
|
|
}
|
|
return res
|
|
})
|
|
|
|
// res.json(v) — serialize v as JSON, set Content-Type.
|
|
_ = res.Set("json", func(call goja.FunctionCall) goja.Value {
|
|
var v any
|
|
if len(call.Arguments) > 0 {
|
|
v = call.Argument(0).Export()
|
|
}
|
|
b, err := jsonMarshal(v)
|
|
if err != nil {
|
|
panic(vm.NewGoError(err))
|
|
}
|
|
resp.body = b
|
|
resp.isJSON = true
|
|
resp.written = true
|
|
return res
|
|
})
|
|
|
|
// res.send(v) — string/bytes body, no forced Content-Type.
|
|
_ = res.Set("send", func(call goja.FunctionCall) goja.Value {
|
|
if len(call.Arguments) > 0 {
|
|
arg := call.Argument(0)
|
|
if b, ok := arg.Export().([]byte); ok {
|
|
resp.body = b
|
|
} else {
|
|
resp.body = []byte(arg.String())
|
|
}
|
|
}
|
|
resp.written = true
|
|
return res
|
|
})
|
|
|
|
return res
|
|
}
|
|
|
|
// replay writes the captured JS response onto the Fiber Ctx.
|
|
func replay(fc fiber.Ctx, resp *jsResponse) error {
|
|
for k, v := range resp.headers {
|
|
fc.Set(k, v)
|
|
}
|
|
fc.Status(resp.status)
|
|
if resp.isJSON {
|
|
fc.Set(fiber.HeaderContentType, fiber.MIMEApplicationJSON)
|
|
}
|
|
if !resp.written || len(resp.body) == 0 {
|
|
return nil
|
|
}
|
|
return fc.Send(resp.body)
|
|
}
|
|
|
|
func isJSONContentType(ct string) bool {
|
|
for i := 0; i+4 <= len(ct); i++ {
|
|
if ct[i:i+4] == "json" {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|