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.
116 lines
3.7 KiB
Go
116 lines
3.7 KiB
Go
package middleware
|
|
|
|
import (
|
|
"encoding/json"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/gwmw"
|
|
"github.com/yetone/magpie/internal/middleware"
|
|
"github.com/yetone/magpie/internal/plugin"
|
|
"github.com/yetone/magpie/internal/pluginrt"
|
|
"github.com/yetone/magpie/internal/routes"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
"github.com/yetone/magpie/internal/testenv"
|
|
"github.com/yetone/magpie/internal/usage"
|
|
)
|
|
|
|
func TestMain(m *testing.M) { testenv.Main(m) }
|
|
|
|
func manifest(t *testing.T) pluginrt.Manifest {
|
|
t.Helper()
|
|
for _, m := range pluginrt.Registered() {
|
|
if m.ID == "middleware" {
|
|
return m
|
|
}
|
|
}
|
|
t.Fatal("middleware not registered")
|
|
return pluginrt.Manifest{}
|
|
}
|
|
|
|
func sandbox(t *testing.T) {
|
|
t.Helper()
|
|
home := t.TempDir()
|
|
t.Setenv("HOME", home)
|
|
t.Setenv("USERPROFILE", home)
|
|
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "config"))
|
|
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, "cache"))
|
|
}
|
|
|
|
// On, the JS middleware chain is the gateway's agent middleware; off, the
|
|
// gateway has none; on again, it is back.
|
|
func TestOnServesOffDoesNot(t *testing.T) {
|
|
sandbox(t)
|
|
rt := pluginrt.New([]pluginrt.Manifest{manifest(t)})
|
|
defer rt.Stop()
|
|
served := func(want bool) {
|
|
t.Helper()
|
|
if got := len(gwmw.Agents()) == 1 && gwmw.Agents()[0] == gwmw.Agent(middleware.Chain{}); got != want || !want && len(gwmw.Agents()) != 0 {
|
|
t.Fatalf("chain served: %v, want %v (%+v)", gwmw.Agents(), want, rt.Statuses())
|
|
}
|
|
}
|
|
served(false)
|
|
rt.Reconcile(map[string]bool{"middleware": true}, nil)
|
|
served(true)
|
|
rt.Reconcile(map[string]bool{"middleware": false}, nil)
|
|
served(false)
|
|
rt.Reconcile(map[string]bool{"middleware": true}, nil)
|
|
served(true)
|
|
}
|
|
|
|
// In use while plugins.json has a middleware on.
|
|
func TestInUse(t *testing.T) {
|
|
sandbox(t)
|
|
t.Cleanup(plugin.Settle)
|
|
m := manifest(t)
|
|
middleware.Reload()
|
|
if n, err := m.InUse(); err != nil || n != 0 {
|
|
t.Fatalf("no plugins: %d %v", n, err)
|
|
}
|
|
mw := filepath.Join(t.TempDir(), "a.middleware.js")
|
|
os.WriteFile(mw, []byte(`export function onRequest(body) { return body; }`), 0o644)
|
|
b, _ := json.Marshal(plugin.List{Plugins: []plugin.Entry{{Spec: mw}}})
|
|
os.MkdirAll(settings.Dir(), 0o755)
|
|
os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), b, 0o644)
|
|
middleware.Reload()
|
|
defer middleware.Reload()
|
|
if n, err := m.InUse(); err != nil || n != 1 {
|
|
t.Fatalf("one middleware: %d %v", n, err)
|
|
}
|
|
}
|
|
|
|
// On, while the gateway serves, a JS gateway plugin's strategies are
|
|
// routings and its onUsage is an observer; off, neither (a pool routed by
|
|
// one goes in its listed order); on again, they are back.
|
|
func TestOnServesStrategies(t *testing.T) {
|
|
sandbox(t)
|
|
t.Cleanup(plugin.Settle)
|
|
gw := filepath.Join(t.TempDir(), "a.gateway.js")
|
|
os.WriteFile(gw, []byte(`export const strategies = { x: (p, s) => s.map((_, i) => i) }; export function onUsage(row) {}`), 0o644)
|
|
b, _ := json.Marshal(plugin.List{Plugins: []plugin.Entry{{Spec: gw}}})
|
|
os.MkdirAll(settings.Dir(), 0o755)
|
|
os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), b, 0o644)
|
|
middleware.Reload()
|
|
defer middleware.Reload()
|
|
stop := usage.ServeObservers()
|
|
defer stop()
|
|
rt := pluginrt.New([]pluginrt.Manifest{manifest(t)})
|
|
defer rt.Stop()
|
|
if routes.Served("a/x") {
|
|
t.Fatal("served before the plugin is on")
|
|
}
|
|
rt.Reconcile(map[string]bool{"middleware": true}, nil)
|
|
if !routes.Served("a/x") || len(usage.Observers()) != 1 {
|
|
t.Fatalf("on: served %v, observers %d", routes.Served("a/x"), len(usage.Observers()))
|
|
}
|
|
rt.Reconcile(map[string]bool{"middleware": false}, nil)
|
|
if routes.Served("a/x") || len(usage.Observers()) != 0 {
|
|
t.Fatal("off: still served")
|
|
}
|
|
rt.Reconcile(map[string]bool{"middleware": true}, nil)
|
|
if !routes.Served("a/x") {
|
|
t.Fatal("on again: not served")
|
|
}
|
|
}
|