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.
85 lines
3.7 KiB
Go
85 lines
3.7 KiB
Go
package cli
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/middleware"
|
|
"github.com/yetone/magpie/internal/plugin"
|
|
"github.com/yetone/magpie/internal/testenv"
|
|
)
|
|
|
|
// magpie plugin says which plugins are gateway middleware and their hooks,
|
|
// or why one didn't load; a middleware plugin has no provider to sign in
|
|
// to, so the list had nothing under it.
|
|
func TestPluginListSaysMiddleware(t *testing.T) {
|
|
bun := testenv.Bun(t)
|
|
groupsHome(t)
|
|
// the Bun the other plugin tests run on, not one downloaded from
|
|
// GitHub (#1922)
|
|
t.Setenv("MAGPIE_BUN", bun)
|
|
t.Cleanup(plugin.Settle) // what adding the plugins told ends with the test
|
|
dir := t.TempDir()
|
|
good := filepath.Join(dir, "alias.middleware.js")
|
|
bad := filepath.Join(dir, "bad.middleware.js")
|
|
// a module with only a strategy and onUsage has no hooks, and the
|
|
// list had nothing after "gateway middleware" for it
|
|
pick := filepath.Join(dir, "pick.gateway.js")
|
|
os.WriteFile(pick, []byte("export const strategies = { last: (p, s) => s.map((_, i) => i).reverse() }\nexport function onUsage(row) {}\n"), 0o644)
|
|
os.WriteFile(good, []byte("export const events = [\"message_start\"]\nexport function onRequest(b, ctx) {}\nexport function onEvent(e, ctx) {}\n"), 0o644)
|
|
os.WriteFile(bad, []byte("export function onRequest( {\n"), 0o644)
|
|
for _, spec := range []string{good, bad, pick} {
|
|
if _, err := plugin.Add(context.Background(), spec); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
middleware.Reload()
|
|
out, err := stdoutOf(t, func() error { return listPlugins(context.Background(), false) })
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !strings.Contains(out, "gateway middleware onRequest, onEvent") {
|
|
t.Errorf("the middleware's hooks aren't listed:\n%s", out)
|
|
}
|
|
if !strings.Contains(out, "gateway middleware routings pick/last · onUsage") {
|
|
t.Errorf("the module's routing and onUsage aren't listed:\n%s", out)
|
|
}
|
|
if !strings.Contains(out, "didn't load: ") || !strings.Contains(out, "SyntaxError") {
|
|
t.Errorf("the broken middleware doesn't say why:\n%s", out)
|
|
}
|
|
js, _ := stdoutOf(t, func() error { return listPlugins(context.Background(), true) })
|
|
if !strings.Contains(js, `"middleware"`) || !strings.Contains(js, `"message_start"`) {
|
|
t.Errorf("--json has no middleware:\n%s", js)
|
|
}
|
|
}
|
|
|
|
// magpie plugin off, on and rm take a plugin's short name, as options
|
|
// does: `magpie plugin off think-tags` said there was no such plugin.
|
|
func TestPluginOnOffRmShortName(t *testing.T) {
|
|
groupsHome(t)
|
|
t.Cleanup(plugin.Settle)
|
|
dir := filepath.Join(t.TempDir(), "middleware-zz-tags")
|
|
os.MkdirAll(dir, 0o755)
|
|
os.WriteFile(filepath.Join(dir, "package.json"), []byte(`{"name": "@magpie-community/middleware-zz-tags", "magpie": {"middleware": "./zz.middleware.js"}}`), 0o644)
|
|
os.WriteFile(filepath.Join(dir, "zz.middleware.js"), []byte("export function onRequest(b) {}\n"), 0o644)
|
|
if _, err := plugin.Add(context.Background(), dir); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
off := func() bool { return plugin.Load().Plugins[0].Off }
|
|
if _, err := stdoutOf(t, func() error { return pluginCmd([]string{"plugin", "off", "zz-tags"}) }); err != nil || !off() {
|
|
t.Fatalf("off by short name: err %v, off %v", err, off())
|
|
}
|
|
if _, err := stdoutOf(t, func() error { return pluginCmd([]string{"plugin", "on", "zz-tags"}) }); err != nil || off() {
|
|
t.Fatalf("on by short name: err %v, off %v", err, off())
|
|
}
|
|
if _, err := stdoutOf(t, func() error { return pluginCmd([]string{"plugin", "rm", "zz-tags"}) }); err != nil || len(plugin.Load().Plugins) != 0 {
|
|
t.Fatalf("rm by short name: err %v, left %v", err, plugin.Load().Plugins)
|
|
}
|
|
if err := pluginCmd([]string{"plugin", "off", "nothing-here"}); err == nil {
|
|
t.Error("a name no plugin has was taken")
|
|
}
|
|
}
|