Files
magpie/internal/middleware/run.go
T
yetone 3f913b3de6 plugins: a JS gateway plugin serves routings (strategies) and watches usage rows (onUsage); plugins/middleware is "JS gateway plugins" (P4)
A plugin's gateway module (magpie.middleware, or its alias magpie.gateway,
or a *.gateway.js file) may now export, besides onRequest/onEvent/onResponse:

- strategies: {name: (pool, seats, options) => order}. Each is a routing
  "<short name>/<name>", registered with routes.Register while the plugin is
  on and loaded and removed when it goes off or reloads. Seats are
  routes.Seat in camelCase JSON. 20ms each; it fails open: a throw, a timeout
  or a result that isn't an order of the seats means the listed order. The
  failure is counted and logged, rate-limited. A file's name is made into a
  routing-safe prefix.
- onUsage(row, options): gets an allow-listed usage row (no bodies, prompts,
  error text, sessions or request ids). The rows come from a bounded queue
  (1024) with one worker, off the request path; a full queue drops the row
  and counts it, and a request never waits. 250ms each.

plugins/middleware is renamed "JS gateway plugins", with a new Sub
(en/zh/zh-TW/ja/de). It registers usage.Observe(middleware.Points()). Off,
no JS hook, strategy or onUsage runs. InUse is unchanged.

providers.json keeps a routing of the form <plugin>/<name> as saved
(provider.PluginRouting) in provider and group Save, whether or not a
plugin serves it now. Before this, `group set g routing=pick/last`
stored nothing.

GUI: the settings state carries jsRoutings. Provider and group routing
pickers offer the served ones, marked data-feature=middleware. A saved
routing that no plugin serves now shows as it is, with a hint. The
Plugins page's line shows routings, how often they were asked, onUsage
rows and dropped rows. The CLI accepts `group set <id> routing=<plugin>/<name>`.
`magpie plugin` lists a module's routings and onUsage; a strategy-only
module had printed nothing after "gateway middleware".

Docs: docs/subsystems/gateway-middleware.md (Routings and usage rows,
limits, verification) and plugin-runtime.md (P4: community plugins at
every point). site/public/docs plugins.html in en, zh and ja has an
example: internal/middleware/testdata/spread.gateway.js, which
TestDocsExample runs.

What was run (worktree on 4df1ba0c6, -p 2):
- gofmt -l: clean. go vet on internal/{middleware,cli,gui,plugin,provider}
  and plugins/...: darwin, GOOS=linux -tags nogui, GOOS=windows; all
  clean, run after the last Go change.
- go test, after the last Go change: internal/middleware ok,
  plugins/middleware ok, internal/provider ok (210s), internal/cli ok
  (203s). Earlier in the work: internal/plugin ok (385s), internal/pluginrt
  ok, internal/gui (Go) ok (320s), and plugins/... ok. The first
  plugins/... run printed a bare FAIL line that `tail` cut off before its
  cause showed. The rerun was all ok; the cause is unknown.
- GUI, both engines (routing-*, group-*, builtins, i18n-keys, gui-de/ja/zh-tw,
  plugin-middleware): 1220 tests, 1204 pass, 16 fail.
  - routing-manual (4): mine. A group's own "manual" was offered a second
    time as a routing no plugin serves. Fixed in client.js withJS. The
    coordinator is rerunning routing-manual, keys-fold, group-fold,
    intent-entry and routing-js alone in both engines, so that rerun is
    not recorded here.
  - routing-model-rest: red alone too, and red on untouched 4df1ba0c6
    (3/20). It is #2115; I commented there with the webkit cases.
  - group-member-weight webkit de 420 is #2387.
  - group-from-model-add webkit zh: it passes alone 2 of 2. Under load it
    waits a fixed 2s for the save post. Filed as #2388.
  - routing-keys-fold (webkit zh/ja/de), routing-group-fold (goto timeout)
    and routing-intent-entry (browser launch timeout 180s) are load
    timeouts. The coordinator is rerunning them alone.
- routing-js.test.cjs (new) passed in chromium en and zh, before the full run.

Broken by hand, each test went red, then restored:
- the permutation check: TestStrategyFailsOpen;
- the queue's non-blocking send: TestOnUsageNeverBlocks ("Ledger waited
  2.04s");
- the allow-list: TestUsageRowAllowList;
- unregister on off: TestStrategiesServedWhileOn and
  TestStrategiesStopWithServe;
- the CLI pattern: TestParseRoutingStays;
- Observe in plugins/middleware: TestOnServesStrategies;
- PluginRouting in provider.go and in group.go: TestPluginRoutingKept;
- the prefix sanitizing: TestRoutingFromFileName;
- the CLI list line: TestPluginListSaysMiddleware;
- the GUI's data-feature mark and its unserved-saved entry: routing-js.

Real use: a sandbox HOME, the gateway served on 127.0.0.1:3682 by a
-tags nogui build, a fake vendor on 3681, and providers fa (key ka) and
fb (key kb) in group g. pick.gateway.js has strategy last (reverse) and an
onUsage that logs.
- `group set g routing=pick/last` stored it.
- A request to group/g reached the vendor with Bearer kb, and the
  "usage-row fb m in=5 keys=17" line was logged.
- `plugin off pick.gateway.js`: Bearer ka (listed order), no onUsage,
  routing still pick/last.
- `plugin on`: Bearer kb and onUsage again.
- `plugin builtin off middleware` says "in use and stays on", as InUse
  should.
- Not tried: the GUI against that gateway, or a real vendor account.
2026-10-15 22:36:59 +08:00

414 lines
9.8 KiB
Go

package middleware
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"strings"
"time"
"github.com/Calcium-Ion/moejs"
"github.com/yetone/magpie/internal/gwmw"
)
func jsonMarshal(v any) ([]byte, error) { return json.Marshal(v) }
// Info is what a request's hooks are told of it, in ctx.
type Info = gwmw.Info
// Reject is a request a middleware turned away (ctx.reject).
type Reject = gwmw.Reject
// Chain is the JS middleware as one agent middleware of the gateway's
// middleware point (gwmw.Use, by plugins/middleware): every middleware
// plugins.json has on, in its order.
type Chain struct{}
// Begin is Begin, nil when there is no middleware.
func (Chain) Begin(info gwmw.Info) gwmw.Run {
if r := Begin(info); r != nil {
return r
}
return nil
}
// On counts the middleware plugins.json has on, whether or not it loads.
func On() int { return len(middlewares()) }
// Run is the middleware of one request. Each middleware's hooks run in
// one runtime for the whole request, so they share ctx.state.
type Run struct {
set *set
info []byte // Info as JSON
insts []*inst
ctxs []moejs.Value
rejected *Reject
status int
}
// Begin starts a request's middleware; nil when there is none, and a nil
// Run does nothing.
func Begin(info Info) *Run {
s := current()
if s == nil || !s.hooked {
return nil
}
b, _ := json.Marshal(info)
return &Run{set: s, info: b, insts: make([]*inst, len(s.list)), ctxs: make([]moejs.Value, len(s.list))}
}
// End gives the runtimes back.
func (r *Run) End() {
if r == nil {
return
}
for i, in := range r.insts {
if in != nil {
r.set.list[i].put(in)
r.insts[i] = nil
}
}
}
// acquire is middleware i's runtime for this request and its ctx: the
// request's Info, the plugin's options, a state of its own and reject.
func (r *Run) acquire(i int) (*inst, moejs.Value, error) {
if in := r.insts[i]; in != nil {
return in, r.ctxs[i], nil
}
m := r.set.list[i]
in, err := m.get()
if err != nil {
return nil, moejs.Undefined(), err
}
in.run = r
b := make([]byte, 0, len(r.info)+len(m.options)+32)
b = append(b, r.info[:len(r.info)-1]...)
b = append(b, `,"options":`...)
b = append(b, m.options...)
b = append(b, `,"state":{}}`...)
ctx, err := in.rt.ParseJSON(b)
if err == nil {
realm := in.rt.Realm()
err = realm.SetV(ctx, realm.KeyFromGoString("reject"), in.rt.Function("reject", 2, r.reject))
}
if err != nil {
m.put(in)
return nil, moejs.Undefined(), err
}
r.insts[i], r.ctxs[i] = in, ctx
return in, ctx, nil
}
// reject is ctx.reject(status, message): onRequest turns the request
// away, and it gets this answer in the agent's API's error shape.
func (r *Run) reject(realm *moejs.Realm, _ moejs.Value, args []moejs.Value) (moejs.Value, error) {
j := Reject{Status: http.StatusForbidden, Message: "turned away by a gateway middleware"}
if a := moejs.Arg(args, 0); a.IsNumber() {
if n := int(a.AsNumber()); n >= 400 && n <= 599 {
j.Status = n
}
}
if a := moejs.Arg(args, 1); a.IsString() {
if s, err := realm.ToString(a); err == nil {
j.Message = s.GoString()
}
}
if r.rejected == nil {
r.rejected = &j
}
return moejs.Undefined(), nil
}
// Request runs each onRequest on body, in turn: what one returns is the
// body the next is given, and undefined leaves it as it was. A hook that
// throws or takes too long leaves it as it was too. A non-nil Reject is a
// request a hook turned away.
func (r *Run) Request(body []byte) ([]byte, *Reject) {
if r == nil {
return body, nil
}
for i, m := range r.set.list {
if !m.hasReq {
continue
}
out, err := r.apply(i, m.onReq, requestLimit, body, nil)
if err != nil {
m.fail("onRequest", err)
continue
}
if r.rejected != nil {
return body, r.rejected
}
if out != nil {
body = out
}
}
return body, nil
}
var errDropped = errors.New("dropped")
// apply calls h on the JSON in data; the JSON it returned, nil for
// undefined, or errDropped for null.
func (r *Run) apply(i int, h moejs.Hook, limit time.Duration, data []byte, status *int) ([]byte, error) {
// a call's time is all it costs the request: the JSON read into the
// runtime and written back out, which is most of it on a large body,
// as well as the hook
m := r.set.list[i]
start := time.Now()
defer func() {
m.calls.Add(1)
m.nanos.Add(int64(time.Since(start)))
}()
in, ctx, err := r.acquire(i)
if err != nil {
return nil, err
}
if status != nil {
realm := in.rt.Realm()
if err := realm.SetV(ctx, realm.KeyFromGoString("status"), moejs.Int(int64(*status))); err != nil {
return nil, err
}
}
v, err := in.rt.ParseJSON(data)
if err != nil {
return nil, err
}
res, err := in.call(h, limit, v, ctx)
switch {
case err != nil:
return nil, err
case res.IsUndefined():
return nil, nil
case res.IsNull():
return nil, errDropped
case !res.IsObject():
return nil, errors.New("returned neither an object, null nor undefined")
}
return in.rt.AppendJSON(nil, res)
}
// Wrap wraps w so each onEvent sees the reply's stream event by event,
// and each onResponse a whole JSON reply; w as it is when no middleware
// has either. done writes what the wrapper still holds.
func (r *Run) Wrap(w http.ResponseWriter) (http.ResponseWriter, func()) {
if r == nil {
return w, func() {}
}
ev, resp := false, false
for _, m := range r.set.list {
ev = ev || m.hasEv
resp = resp || m.hasResp
}
if !ev && !resp {
return w, func() {}
}
rw := &writer{w: w, run: r, ev: ev, resp: resp, status: http.StatusOK}
return rw, rw.finish
}
const (
unknown = iota
stream
whole
asIs
)
type writer struct {
w http.ResponseWriter
run *Run
ev, resp bool
mode int
status int
buf bytes.Buffer
done bool
}
func (rw *writer) Header() http.Header { return rw.w.Header() }
// Unwrap is for http.ResponseController.
func (rw *writer) Unwrap() http.ResponseWriter { return rw.w }
func (rw *writer) decide(first []byte) {
h := rw.w.Header()
ct := h.Get("Content-Type")
switch {
case h.Get("Content-Encoding") != "" && !strings.EqualFold(h.Get("Content-Encoding"), "identity"):
rw.mode = asIs
case strings.Contains(ct, "event-stream"):
rw.mode = stream
case ct == "" && (bytes.HasPrefix(first, []byte("event:")) || bytes.HasPrefix(first, []byte("data:"))):
rw.mode = stream
case strings.Contains(ct, "json"):
rw.mode = whole
default:
rw.mode = asIs
}
if rw.mode == stream && !rw.ev || rw.mode == whole && !rw.resp {
rw.mode = asIs
}
if rw.mode != asIs {
h.Del("Content-Length")
}
}
func (rw *writer) WriteHeader(code int) {
rw.status = code
if rw.mode == unknown && rw.w.Header().Get("Content-Type") != "" {
rw.decide(nil)
}
rw.w.WriteHeader(code)
}
func (rw *writer) Write(p []byte) (int, error) {
if rw.mode == unknown {
rw.decide(p)
}
switch rw.mode {
case asIs:
return rw.w.Write(p)
case whole:
return rw.buf.Write(p)
}
rw.buf.Write(p)
for {
b := rw.buf.Bytes()
i, n := eventEnd(b)
if i < 0 {
break
}
ev := b[:i+n]
err := rw.event(ev)
rw.buf.Next(i + n)
if err != nil {
return len(p), err
}
}
return len(p), nil
}
func (rw *writer) Flush() {
if f, ok := rw.w.(http.Flusher); ok && rw.mode != whole {
f.Flush()
}
}
func (rw *writer) finish() {
if rw.done {
return
}
rw.done = true
switch rw.mode {
case whole:
body := rw.buf.Bytes()
for i, m := range rw.run.set.list {
if !m.hasResp {
continue
}
out, err := rw.run.apply(i, m.onResp, requestLimit, body, &rw.status)
switch {
case errors.Is(err, errDropped):
m.fail("onResponse", errors.New("returned null; a whole reply can't be dropped"))
case err != nil:
m.fail("onResponse", err)
case out != nil:
body = out
}
}
rw.w.Write(body)
case stream:
if rw.buf.Len() > 0 {
rw.w.Write(rw.buf.Bytes())
}
}
rw.Flush()
}
// event runs each onEvent that wants it on one event of the stream, and
// writes it, or nothing when one dropped it.
func (rw *writer) event(ev []byte) error {
name, data, pre, post, ok := splitEvent(ev)
if !ok {
_, err := rw.w.Write(ev)
return err
}
changed := false
for i, m := range rw.run.set.list {
if !m.hasEv || m.events != nil && !m.events[name] {
continue
}
out, err := rw.run.apply(i, m.onEv, eventLimit, data, nil)
switch {
case errors.Is(err, errDropped):
return nil
case err != nil:
m.fail("onEvent", err)
case out != nil:
data, changed = out, true
}
}
if !changed {
_, err := rw.w.Write(ev)
return err
}
out := make([]byte, 0, len(pre)+len(data)+len(post))
_, err := rw.w.Write(append(append(append(out, pre...), data...), post...))
return err
}
// eventEnd is where the first complete event in b ends, and the length of
// the blank line that ends it.
func eventEnd(b []byte) (int, int) {
i := bytes.Index(b, []byte("\n\n"))
j := bytes.Index(b, []byte("\r\n\r\n"))
switch {
case i < 0 && j < 0:
return -1, 0
case j >= 0 && (i < 0 || j < i):
return j, 4
default:
return i, 2
}
}
// splitEvent finds the one data line of an event that has JSON in it:
// what comes before the JSON, the JSON, and what comes after it.
func splitEvent(ev []byte) (name string, data, pre, post []byte, ok bool) {
at, off, atOff := -1, 0, 0
var line []byte
for rest := ev; len(rest) > 0; {
l := rest
if k := bytes.IndexByte(rest, '\n'); k >= 0 {
l = rest[:k+1]
}
rest = rest[len(l):]
t := bytes.TrimRight(l, "\r\n")
switch {
case bytes.HasPrefix(t, []byte("event:")):
name = strings.TrimSpace(string(t[6:]))
case bytes.HasPrefix(t, []byte("data:")):
if at >= 0 {
return "", nil, nil, nil, false // data over more than one line
}
at, atOff, line = off, off, t
}
off += len(l)
}
if at < 0 {
return "", nil, nil, nil, false
}
start := 5
if len(line) > 5 && line[5] == ' ' {
start = 6
}
// an event's JSON is an object in every API; data: [DONE] isn't JSON
d := line[start:]
if len(d) == 0 || d[0] != '{' {
return "", nil, nil, nil, false
}
return name, d, ev[:atOff+start], ev[atOff+len(line):], true
}