From 9f1ec09bd44295fb02a1224d6082fe1b4c32b6c2 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 29 Nov 2026 19:12:56 +0100 Subject: [PATCH 01/11] test(pluginkit): pin the promises a plugin makes to its host --- pluginkit/features/plugin-checks.feature | 102 +++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 pluginkit/features/plugin-checks.feature diff --git a/pluginkit/features/plugin-checks.feature b/pluginkit/features/plugin-checks.feature new file mode 100644 index 0000000..0bf76ef --- /dev/null +++ b/pluginkit/features/plugin-checks.feature @@ -0,0 +1,102 @@ +Feature: Checking the promises a plugin makes to its host from its own tests + A downstream application lends plugin authors a check they run from a + plugin's own tests, with a time limit the application sets. The check + holds a plugin to the promises of the plugin contract: Register answers + a plugin with its manifest's id within the time limit, Routes and + PublicPaths answer before Start runs, Stop works on a plugin that never + started, and Start runs again after Stop. Each check registers a new + plugin from new dependencies, so one broken promise does not hide + another, and a call that never returns is cut at the time limit. Each + finding names its rule, the problem and the fix. An application can + also check one manifest's id against the ids it reserves and the names + the generated wiring uses. + + Scenario: A plugin that keeps every promise gives no finding + Given the plugin "events" keeps every promise + When the application checks the lifecycle of "events" with a time limit of 200ms + Then the check gives no finding + + Scenario: A plugin with no routes and no public paths gives no finding + Given the plugin "events" has no routes and no public paths + When the application checks the lifecycle of "events" with a time limit of 200ms + Then the check gives no finding + + Scenario Outline: A plugin whose Register breaks a promise gives that finding alone + Given the plugin "events" + When the application checks the lifecycle of "events" with a time limit of 200ms + Then the check gives one finding, under the rule "" + And its problem reads: + And its fix reads: + + Examples: + | fault | rule | problem | fix | + | answers the error "no database" from Register | register | Register answered the error: no database | Return the plugin from Register with no error, and leave work that can fail to Start. | + | panics with "boom" in Register | register | Register panicked: boom | Return the plugin from Register with no error, and leave work that can fail to Start. | + | answers no plugin from Register | register | Register answered no plugin | Return the plugin Register builds. | + | calls itself "news" | register | Register answered a plugin that calls itself "news", not "events" | Make ID return "events", the id in plugin.json. | + | takes 1s in Register | register-time | Register did not return within 200ms | Keep Register to building the plugin, and open connections or read data in Start. | + + Scenario Outline: A plugin that breaks a promise after Register is named under its rule + Given the plugin "events" + When the application checks the lifecycle of "events" with a time limit of 200ms + Then the check gives one finding, under the rule "" + And its problem reads: + And its fix reads: + + Examples: + | fault | rule | problem | fix | + | answers no handler from Routes | routes-before-start | Routes before Start answered no handler | Build the handler and the paths in Register, so Routes and PublicPaths answer whether or not Start ran. | + | panics with "boom" in Routes | routes-before-start | Routes before Start panicked: boom | Build the handler and the paths in Register, so Routes and PublicPaths answer whether or not Start ran. | + | never returns from Routes | routes-before-start | Routes before Start did not return within 200ms | Build the handler and the paths in Register, so Routes and PublicPaths answer whether or not Start ran. | + | panics with "boom" in PublicPaths | routes-before-start | PublicPaths before Start panicked: boom | Build the handler and the paths in Register, so Routes and PublicPaths answer whether or not Start ran. | + | answers the error "nothing to close" from Stop before any Start | stop-without-start | Stop before any Start answered the error: nothing to close | Let Stop release only what Start opened, and return nil when Start never ran. | + | panics with "boom" in Stop before any Start | stop-without-start | Stop before any Start panicked: boom | Let Stop release only what Start opened, and return nil when Start never ran. | + | never returns from Stop before any Start | stop-without-start | Stop before any Start did not return within 200ms | Let Stop release only what Start opened, and return nil when Start never ran. | + | answers the error "no route table" from the first Start | start-stop-again | the first Start answered the error: no route table | Let Start open again what Stop released, and let each call return by the time its context ends. | + | never returns from the first Start | start-stop-again | the first Start did not return within 200ms | Let Start open again what Stop released, and let each call return by the time its context ends. | + | answers the error "already closed" from the Stop after the first Start | start-stop-again | the first Stop answered the error: already closed | Let Start open again what Stop released, and let each call return by the time its context ends. | + | answers the error "already started" from the second Start | start-stop-again | the second Start answered the error: already started | Let Start open again what Stop released, and let each call return by the time its context ends. | + | panics with "boom" in the second Start | start-stop-again | the second Start panicked: boom | Let Start open again what Stop released, and let each call return by the time its context ends. | + | panics with "boom" in the Stop after the second Start | start-stop-again | the second Stop panicked: boom | Let Start open again what Stop released, and let each call return by the time its context ends. | + + Scenario: Each check registers a new plugin, so one broken promise does not hide another + Given the plugin "events" answers no handler from Routes + And the plugin "events" answers the error "nothing to close" from Stop before any Start + And the plugin "events" answers the error "already started" from the second Start + When the application checks the lifecycle of "events" with a time limit of 200ms + Then the check gives these findings, in this order: + | rule | problem | + | routes-before-start | Routes before Start answered no handler | + | stop-without-start | Stop before any Start answered the error: nothing to close | + | start-stop-again | the second Start answered the error: already started | + And every Register of "events" received dependencies built for it alone + + Scenario: A call that never returns is cut at the time limit and the later checks still run + Given the plugin "events" never returns from Routes + And the plugin "events" answers the error "already started" from the second Start + When the application checks the lifecycle of "events" with a time limit of 200ms + Then the check gives these findings, in this order: + | rule | problem | + | routes-before-start | Routes before Start did not return within 200ms | + | start-stop-again | the second Start answered the error: already started | + + Scenario: Start and Stop each get a context that ends at the time limit + Given the plugin "events" keeps every promise + When the application checks the lifecycle of "events" with a time limit of 200ms + Then every Start and Stop of "events" got a context that ends within 200ms of the call + + Scenario Outline: One manifest's id is checked against the reserved ids and the generated wiring + Given a manifest with the id "" and + And the application reserves the ids "core" and "admin" + When the application checks the manifest's id + Then the id check + + Examples: + | id | parts | result | + | events | a backend | passes | + | core | a backend | rejects it with: id "core" is reserved | + | admin | only a frontend | rejects it with: id "admin" is reserved | + | fmt | a backend | rejects it with: id "fmt" collides with the generated Go wiring | + | import | a backend | rejects it with: id "import" collides with the generated Go wiring | + | fmt | only a frontend | passes | + | import | only a frontend | rejects it with: id "import" collides with the generated TypeScript wiring | From d3abb3f980de57d018599c6cf336ef58391b7498 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 29 Nov 2026 19:12:56 +0100 Subject: [PATCH 02/11] feat(pluginkit): check one manifest's id against the reserved ids and the generated wiring --- pluginkit/wire/manifest.go | 2 +- pluginkit/wire/wire.go | 13 ++++-- pluginkit/wire/wire_test.go | 93 ++++++++++++++++++++++++++++++++----- 3 files changed, 92 insertions(+), 16 deletions(-) diff --git a/pluginkit/wire/manifest.go b/pluginkit/wire/manifest.go index bcc7eec..4e03015 100644 --- a/pluginkit/wire/manifest.go +++ b/pluginkit/wire/manifest.go @@ -280,7 +280,7 @@ func checkShape(m manifest) error { ) } -// Read reads one plugin's manifest from the plugin's own file system, leaving the folder match and refused ids to Load. +// Read reads one plugin's manifest from its file system, leaving the folder match to Load and the id check to CheckID. func Read(plugin fs.FS) (Manifest, error) { data, err := fs.ReadFile(plugin, "plugin.json") if err != nil { diff --git a/pluginkit/wire/wire.go b/pluginkit/wire/wire.go index a95a69e..8ca7b65 100644 --- a/pluginkit/wire/wire.go +++ b/pluginkit/wire/wire.go @@ -119,12 +119,17 @@ var tsOwned = map[string]bool{ "arguments": true, "plugins": true, } -// refuseReserved rejects an id the application reserves or an import alias of the generated wiring cannot take. -func refuseReserved(m manifest, reserved []string) error { +// collidesWithGoWiring reports whether id is a Go keyword or a name the generated Go wiring uses. +func collidesWithGoWiring(id string) bool { + return token.IsKeyword(id) || goOwned[id] +} + +// CheckID rejects an id the application reserves or one an import alias of the generated wiring cannot take. +func CheckID(m Manifest, reserved []string) error { switch { case slices.Contains(reserved, m.ID): return fmt.Errorf("id %q is reserved", m.ID) - case m.Backend != "" && (token.IsKeyword(m.ID) || goOwned[m.ID]): + case m.Backend != "" && collidesWithGoWiring(m.ID): return fmt.Errorf("id %q collides with the generated Go wiring", m.ID) case m.Frontend != "" && tsOwned[m.ID]: return fmt.Errorf("id %q collides with the generated TypeScript wiring", m.ID) @@ -145,7 +150,7 @@ func loadRoots(dir string, roots, reserved []string) ([]manifest, error) { if previous, ok := seen[m.ID]; ok { return nil, fmt.Errorf("pluginwire: plugin %s appears under %s and %s", m.ID, previous, pluginRoot) } - if err := refuseReserved(m, reserved); err != nil { + if err := CheckID(Manifest(m), reserved); err != nil { return nil, fmt.Errorf("pluginwire: %s: %w", filepath.Join(dir, pluginRoot, m.ID, "plugin.json"), err) } seen[m.ID] = pluginRoot diff --git a/pluginkit/wire/wire_test.go b/pluginkit/wire/wire_test.go index 19233a5..4707294 100644 --- a/pluginkit/wire/wire_test.go +++ b/pluginkit/wire/wire_test.go @@ -750,7 +750,27 @@ func TestRunRefusesAnIDTheApplicationReserves(t *testing.T) { } } -func TestRefuseReservedCoversEveryNameAnAliasCannotTake(t *testing.T) { +// backendManifest returns the manifest of a plugin with the id and only a backend. +func backendManifest(id string) Manifest { + return Manifest{ID: id, Backend: "example.com/myapp/plugins/" + id} +} + +// frontendManifest returns the manifest of a plugin with the id and only a frontend. +func frontendManifest(id string) Manifest { + return Manifest{ID: id, Frontend: "@myapp/plugin-" + id} +} + +// backendAndFrontendManifest returns the manifest of a plugin with the id, a backend and a frontend. +func backendAndFrontendManifest(id string) Manifest { + m := backendManifest(id) + m.Frontend = frontendManifest(id).Frontend + return m +} + +// reservedIDs are the ids the application reserves in the CheckID tests. +var reservedIDs = []string{"core", "admin", "main"} + +func TestCheckIDCoversEveryNameAnAliasCannotTake(t *testing.T) { t.Parallel() goNames := []string{ @@ -768,18 +788,69 @@ func TestRefuseReservedCoversEveryNameAnAliasCannotTake(t *testing.T) { "eval", "arguments", "plugins", } for _, id := range goNames { - want := `id "` + id + `" collides with the generated Go wiring` - if err := refuseReserved(manifest{ID: id, Backend: "example.com/myapp/plugins/" + id}, nil); err == nil || - err.Error() != want { - t.Errorf("refuseReserved(backend %s) = %v, want %q", id, err, want) - } + assertErrorText(t, CheckID(backendManifest(id), nil), `id "`+id+`" collides with the generated Go wiring`) } for _, id := range tsNames { - want := `id "` + id + `" collides with the generated TypeScript wiring` - if err := refuseReserved(manifest{ID: id, Frontend: "@myapp/plugin-" + id}, nil); err == nil || - err.Error() != want { - t.Errorf("refuseReserved(frontend %s) = %v, want %q", id, err, want) - } + assertErrorText(t, CheckID(frontendManifest(id), nil), + `id "`+id+`" collides with the generated TypeScript wiring`) + } +} + +func TestCheckIDRejectsAnIDTheApplicationReservesOrItsWiringUses(t *testing.T) { + t.Parallel() + + tests := map[string]struct { + m Manifest + want string + }{ + "a reserved id with a backend": { + m: backendManifest("core"), want: `id "core" is reserved`, + }, + "a reserved id with only a frontend": { + m: frontendManifest("admin"), want: `id "admin" is reserved`, + }, + "a reserved id the Go wiring also uses": { + m: backendManifest("main"), want: `id "main" is reserved`, + }, + "a Go keyword with a backend": { + m: backendManifest("func"), want: `id "func" collides with the generated Go wiring`, + }, + "a name the Go wiring uses, with a backend": { + m: backendManifest("fmt"), want: `id "fmt" collides with the generated Go wiring`, + }, + "a name both wirings use, with a backend and a frontend": { + m: backendAndFrontendManifest("import"), want: `id "import" collides with the generated Go wiring`, + }, + "a name the TypeScript wiring uses, with only a frontend": { + m: frontendManifest("class"), want: `id "class" collides with the generated TypeScript wiring`, + }, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + assertErrorText(t, CheckID(tc.m, reservedIDs), tc.want) + }) + } +} + +func TestCheckIDPassesAnIDNeitherReservedNorUsedByItsWiring(t *testing.T) { + t.Parallel() + + tests := map[string]Manifest{ + "a Go keyword with only a frontend": frontendManifest("func"), + "a name the Go wiring uses, with only a frontend": frontendManifest("fmt"), + "a name the TypeScript wiring uses, with only a backend": backendManifest("class"), + "an id no list holds, with a backend and a frontend": backendAndFrontendManifest("events"), + } + for name, m := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + if err := CheckID(m, reservedIDs); err != nil { + t.Errorf("CheckID(%+v) = %v, want nil", m, err) + } + }) } } From cde1815d2c2a0ae9bad4d665a3f5512ec2e77ff0 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 29 Nov 2026 19:12:56 +0100 Subject: [PATCH 03/11] refactor(pluginkit): share the nil check and the value text through an internal package --- pluginkit/hook.go | 16 +--- pluginkit/host.go | 4 +- pluginkit/internal/anyvalue/anyvalue.go | 32 +++++++ pluginkit/internal/anyvalue/anyvalue_test.go | 98 ++++++++++++++++++++ pluginkit/protect.go | 6 +- pluginkit/recover.go | 4 +- pluginkit/registration.go | 18 +--- pluginkit/routes.go | 4 +- 8 files changed, 150 insertions(+), 32 deletions(-) create mode 100644 pluginkit/internal/anyvalue/anyvalue.go create mode 100644 pluginkit/internal/anyvalue/anyvalue_test.go diff --git a/pluginkit/hook.go b/pluginkit/hook.go index 134bfe5..4979729 100644 --- a/pluginkit/hook.go +++ b/pluginkit/hook.go @@ -10,6 +10,8 @@ import ( "runtime/debug" "sync/atomic" "time" + + "github.com/gopherium/framework/pluginkit/internal/anyvalue" ) // HookSettings are the values a hook runs under, each one required. @@ -281,25 +283,15 @@ type outcome struct { func run[C any](ctx context.Context, plugin C, call func(context.Context, C) error) (out *outcome) { defer func() { if recovered := recover(); recovered != nil { - out = &outcome{panicked: true, stack: string(debug.Stack()), text: describe(recovered)} + out = &outcome{panicked: true, stack: string(debug.Stack()), text: anyvalue.Text(recovered)} } }() if err := call(ctx, plugin); err != nil { - return &outcome{err: err, text: describe(err), ended: ctx.Err() != nil && errors.Is(err, ctx.Err())} + return &outcome{err: err, text: anyvalue.Text(err), ended: ctx.Err() != nil && errors.Is(err, ctx.Err())} } return nil } -// describe returns v as fmt prints it, or its type when printing it panics. -func describe(v any) (text string) { - defer func() { - if recover() != nil { - text = fmt.Sprintf("%T whose text panicked", v) - } - }() - return fmt.Sprint(v) -} - // pluginError is a plugin's error with the plugin and the hook named before its text. type pluginError struct { text string diff --git a/pluginkit/host.go b/pluginkit/host.go index 011f787..be73d8b 100644 --- a/pluginkit/host.go +++ b/pluginkit/host.go @@ -8,6 +8,8 @@ import ( "fmt" "net/http" "time" + + "github.com/gopherium/framework/pluginkit/internal/anyvalue" ) var ( @@ -228,7 +230,7 @@ func safeCall(ctx context.Context, id, operation string, fn func(context.Context func guarded(ctx context.Context, name string, fn func(context.Context) error) (err error) { defer func() { if recovered := recover(); recovered != nil { - err = guardedPanic{name: name, value: describe(recovered)} + err = guardedPanic{name: name, value: anyvalue.Text(recovered)} } }() if err := fn(ctx); err != nil { diff --git a/pluginkit/internal/anyvalue/anyvalue.go b/pluginkit/internal/anyvalue/anyvalue.go new file mode 100644 index 0000000..8543a6e --- /dev/null +++ b/pluginkit/internal/anyvalue/anyvalue.go @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package anyvalue answers whether a value of any type holds nothing and the text it prints as. +package anyvalue + +import ( + "fmt" + "reflect" +) + +// IsNil reports whether value holds nothing: a nil interface, pointer, map, slice, channel or function. +func IsNil(value any) bool { + reflectValue := reflect.ValueOf(value) + switch reflectValue.Kind() { + case reflect.Invalid: + return true + case reflect.Pointer, reflect.Map, reflect.Slice, reflect.Chan, reflect.Func: + return reflectValue.IsNil() + default: + return false + } +} + +// Text returns value as fmt.Sprint prints it, or its type when printing it panics. +func Text(value any) (text string) { + defer func() { + if recover() != nil { + text = fmt.Sprintf("%T whose text panicked", value) + } + }() + return fmt.Sprint(value) +} diff --git a/pluginkit/internal/anyvalue/anyvalue_test.go b/pluginkit/internal/anyvalue/anyvalue_test.go new file mode 100644 index 0000000..0df5aa8 --- /dev/null +++ b/pluginkit/internal/anyvalue/anyvalue_test.go @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: Apache-2.0 + +package anyvalue_test + +import ( + "errors" + "testing" + + "github.com/gopherium/framework/pluginkit/internal/anyvalue" +) + +// selfPanicError is an error whose Error panics with the error itself. +type selfPanicError struct{} + +// Error panics with the error itself. +func (selfPanicError) Error() string { + panic(selfPanicError{}) +} + +func TestIsNilAnswersTrueForAValueThatHoldsNothing(t *testing.T) { + t.Parallel() + + var nilPointer *int + var nilError error + tests := map[string]any{ + "a nil interface": nilError, + "a nil pointer": nilPointer, + "a nil map": map[string]int(nil), + "a nil slice": []int(nil), + "a nil channel": (chan int)(nil), + "a nil function": (func())(nil), + } + for name, value := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + if !anyvalue.IsNil(value) { + t.Errorf("IsNil(%#v) = false, want true", value) + } + }) + } +} + +func TestIsNilAnswersFalseForAValueThatHoldsSomething(t *testing.T) { + t.Parallel() + + count := 1 + tests := map[string]any{ + "a pointer": &count, + "a map": map[string]int{}, + "a slice": []int{}, + "a channel": make(chan int), + "a function": func() {}, + "a struct": struct{}{}, + "a zero": 0, + "an error": errors.New("no database"), + } + for name, value := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + if anyvalue.IsNil(value) { + t.Errorf("IsNil(%#v) = true, want false", value) + } + }) + } +} + +func TestTextAnswersWhatFmtPrints(t *testing.T) { + t.Parallel() + + tests := map[string]struct { + value any + want string + }{ + "a string": {"boom", "boom"}, + "an error": {errors.New("no database"), "no database"}, + "a number": {42, "42"}, + "nil": {nil, ""}, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + if got := anyvalue.Text(tc.value); got != tc.want { + t.Errorf("Text(%#v) = %q, want %q", tc.value, got, tc.want) + } + }) + } +} + +func TestTextAnswersTheTypeOfAValueWhoseTextPanics(t *testing.T) { + t.Parallel() + + if got, want := anyvalue.Text(selfPanicError{}), "anyvalue_test.selfPanicError whose text panicked"; got != want { + t.Errorf("Text(selfPanicError{}) = %q, want %q", got, want) + } +} diff --git a/pluginkit/protect.go b/pluginkit/protect.go index e8ff471..c8e6ddf 100644 --- a/pluginkit/protect.go +++ b/pluginkit/protect.go @@ -5,6 +5,8 @@ package pluginkit import ( "context" "net/http" + + "github.com/gopherium/framework/pluginkit/internal/anyvalue" ) // RouteSettings are what every plugin's routes are protected under, one value an application reuses for each plugin. @@ -26,7 +28,7 @@ func Protect(id string, handler http.Handler, publicPaths []string, settings Rou } plugin := &recovered{id: id, handler: handler, settings: settings} protected := settings.Wrap(plugin) - if isNil(protected) { + if anyvalue.IsNil(protected) { panic("pluginkit: Protect: RouteSettings.Wrap answered no handler") } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -46,7 +48,7 @@ func checkRouteSettings(id string, settings RouteSettings) { panic("pluginkit: Protect: the plugin id is empty") case settings.Wrap == nil: panic("pluginkit: Protect: RouteSettings.Wrap is nil") - case isNil(settings.Answer): + case anyvalue.IsNil(settings.Answer): panic("pluginkit: Protect: RouteSettings.Answer is nil") case settings.Report == nil: panic("pluginkit: Protect: RouteSettings.Report is nil") diff --git a/pluginkit/recover.go b/pluginkit/recover.go index 757e16e..828dde0 100644 --- a/pluginkit/recover.go +++ b/pluginkit/recover.go @@ -9,6 +9,8 @@ import ( "net/http" "runtime/debug" "sync/atomic" + + "github.com/gopherium/framework/pluginkit/internal/anyvalue" ) // RouteFailure is one panic of one plugin's handler while it served one request. @@ -63,7 +65,7 @@ func (h *recovered) finish(writer *routeWriter, header http.Header, r *http.Requ begun := writer.begun.Load() || begunBefore(r) h.settings.Report(RouteFailure{ ID: h.id, Method: r.Method, Path: r.URL.Path, Answered: !begun, - Err: panicError("pluginkit: " + h.id + " route panicked: " + describe(caught)), Stack: string(debug.Stack()), + Err: panicError("pluginkit: " + h.id + " route panicked: " + anyvalue.Text(caught)), Stack: string(debug.Stack()), }) if begun { panic(http.ErrAbortHandler) diff --git a/pluginkit/registration.go b/pluginkit/registration.go index 3ef7025..64362bd 100644 --- a/pluginkit/registration.go +++ b/pluginkit/registration.go @@ -6,7 +6,8 @@ import ( "context" "errors" "fmt" - "reflect" + + "github.com/gopherium/framework/pluginkit/internal/anyvalue" ) // errNoPlugin is the failure of a Register that answered neither a plugin nor an error. @@ -48,7 +49,7 @@ func register[D any, P interface{ ID() string }](entry Registration[D, P], deps if registerErr != nil { return registerErr } - if isNil(plugin) { + if anyvalue.IsNil(plugin) { return errNoPlugin } if id := plugin.ID(); id != entry.ID { @@ -58,16 +59,3 @@ func register[D any, P interface{ ID() string }](entry Registration[D, P], deps }) return plugin, err } - -// isNil reports whether plugin holds nothing: a nil interface, pointer, map, slice, channel or function. -func isNil(plugin any) bool { - value := reflect.ValueOf(plugin) - switch value.Kind() { - case reflect.Invalid: - return true - case reflect.Pointer, reflect.Map, reflect.Slice, reflect.Chan, reflect.Func: - return value.IsNil() - default: - return false - } -} diff --git a/pluginkit/routes.go b/pluginkit/routes.go index 1ccc333..3e5061a 100644 --- a/pluginkit/routes.go +++ b/pluginkit/routes.go @@ -6,6 +6,8 @@ import ( "context" "errors" "net/http" + + "github.com/gopherium/framework/pluginkit/internal/anyvalue" ) // errNoHandler is the failure of a Routes that answered no handler. @@ -39,7 +41,7 @@ func RoutesEach[P interface{ ID() string }](plugins []P) RoutesOutcome { func (o *RoutesOutcome) read(id string, plugin any) error { if provider, ok := plugin.(RouteProvider); ok { handler := provider.Routes() - if isNil(handler) { + if anyvalue.IsNil(handler) { return errNoHandler } o.Routes[id] = handler From 7d6af0f7ce469d355337431de347196b4505730e Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 29 Nov 2026 19:12:57 +0100 Subject: [PATCH 04/11] feat(pluginkit): check a plugin's lifecycle promises from its own tests --- pluginkit/plugintest/call.go | 52 ++ pluginkit/plugintest/call_test.go | 125 ++++ pluginkit/plugintest/lifecycle.go | 184 ++++++ pluginkit/plugintest/lifecycle_test.go | 778 +++++++++++++++++++++++++ pluginkit/plugintest/plugintest.go | 24 + 5 files changed, 1163 insertions(+) create mode 100644 pluginkit/plugintest/call.go create mode 100644 pluginkit/plugintest/call_test.go create mode 100644 pluginkit/plugintest/lifecycle.go create mode 100644 pluginkit/plugintest/lifecycle_test.go create mode 100644 pluginkit/plugintest/plugintest.go diff --git a/pluginkit/plugintest/call.go b/pluginkit/plugintest/call.go new file mode 100644 index 0000000..73b3928 --- /dev/null +++ b/pluginkit/plugintest/call.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 + +package plugintest + +import ( + "context" + "time" + + "github.com/gopherium/framework/pluginkit/internal/anyvalue" +) + +// callOutcome is how one call of plugin code ended: what it answered, or the problem that ended it. +type callOutcome[T any] struct { + // answer is what the call returned beside a nil error, and its zero value after a problem. + answer T + // problem says how the call broke its promise, and is empty when it returned nil within the step budget. + problem string + // isOverBudget reports whether the call did not return within the step budget. + isOverBudget bool +} + +// outcomeOf runs call in a goroutine of its own with a context that ends at stepBudget, naming it name in a problem. +func outcomeOf[T any](name string, stepBudget time.Duration, call func(context.Context) (T, error)) callOutcome[T] { + ctx, cancel := context.WithTimeout(context.Background(), stepBudget) + defer cancel() + outcomes := make(chan callOutcome[T], 1) + go func() { + outcomes <- outcomeWithRecover(ctx, name, call) + }() + select { + case outcome := <-outcomes: + return outcome + case <-ctx.Done(): + return callOutcome[T]{problem: name + " did not return within " + stepBudget.String(), isOverBudget: true} + } +} + +// outcomeWithRecover makes call with ctx inside a recover and returns its answer, or the problem of its error or panic. +func outcomeWithRecover[T any]( + ctx context.Context, name string, call func(context.Context) (T, error), +) (outcome callOutcome[T]) { + defer func() { + if value := recover(); value != nil { + outcome = callOutcome[T]{problem: name + " panicked: " + anyvalue.Text(value)} + } + }() + answer, err := call(ctx) + if err != nil { + return callOutcome[T]{problem: name + " answered the error: " + err.Error()} + } + return callOutcome[T]{answer: answer} +} diff --git a/pluginkit/plugintest/call_test.go b/pluginkit/plugintest/call_test.go new file mode 100644 index 0000000..f426071 --- /dev/null +++ b/pluginkit/plugintest/call_test.go @@ -0,0 +1,125 @@ +// SPDX-License-Identifier: Apache-2.0 + +package plugintest + +import ( + "context" + "errors" + "runtime" + "testing" + "testing/synctest" + "time" +) + +// testBudget is the step budget the tests of one call hand outcomeOf. +const testBudget = 50 * time.Millisecond + +// textPanicError is an error whose Error panics with the error's text. +type textPanicError string + +// Error panics with the error's text. +func (e textPanicError) Error() string { + panic(string(e)) +} + +// selfPanicError is an error whose Error panics with the error itself. +type selfPanicError struct{} + +// Error panics with the error itself. +func (selfPanicError) Error() string { + panic(selfPanicError{}) +} + +func TestOutcomeOfAnswersWhatACallReturnedWithinTheStepBudget(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + outcome := outcomeOf("the first Start", testBudget, func(context.Context) (int, error) { + return 42, nil + }) + + if outcome != (callOutcome[int]{answer: 42}) { + t.Errorf("outcome = %+v, want the answer 42 and no problem", outcome) + } + }) +} + +func TestOutcomeOfNamesTheErrorOrThePanicThatEndedACall(t *testing.T) { + t.Parallel() + + tests := map[string]struct { + call func(context.Context) (int, error) + want string + }{ + "an error beside an answer": { + func(context.Context) (int, error) { return 42, errors.New("no route table") }, + "the first Start answered the error: no route table", + }, + "a panic": { + func(context.Context) (int, error) { panic("boom") }, + "the first Start panicked: boom", + }, + "a panic with an error": { + func(context.Context) (int, error) { panic(errors.New("boom")) }, + "the first Start panicked: boom", + }, + "a panic with nil": { + func(context.Context) (int, error) { panic(nil) }, + "the first Start panicked: " + new(runtime.PanicNilError).Error(), + }, + "an error whose text panics": { + func(context.Context) (int, error) { return 0, textPanicError("bad text") }, + "the first Start panicked: bad text", + }, + "a panic whose text panics too": { + func(context.Context) (int, error) { panic(selfPanicError{}) }, + "the first Start panicked: plugintest.selfPanicError whose text panicked", + }, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + outcome := outcomeOf("the first Start", testBudget, tc.call) + + if outcome != (callOutcome[int]{problem: tc.want}) { + t.Errorf("outcome = %+v, want no answer and the problem %q", outcome, tc.want) + } + }) + }) + } +} + +func TestOutcomeOfCutsACallThatDoesNotReturnWithinTheStepBudget(t *testing.T) { + t.Parallel() + + tests := map[time.Duration]string{ + 50 * time.Millisecond: "the first Start did not return within 50ms", + time.Second: "the first Start did not return within 1s", + 1500 * time.Millisecond: "the first Start did not return within 1.5s", + } + for stepBudget, want := range tests { + t.Run(want, func(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + release := make(chan struct{}) + t.Cleanup(func() { close(release) }) + callTime := time.Now() + + outcome := outcomeOf("the first Start", stepBudget, func(context.Context) (int, error) { + <-release + return 42, nil + }) + + if waitTime := time.Since(callTime); waitTime != stepBudget { + t.Errorf("outcomeOf waited %v, want the step budget %v", waitTime, stepBudget) + } + if outcome != (callOutcome[int]{problem: want, isOverBudget: true}) { + t.Errorf("outcome = %+v, want no answer, the problem %q and the budget passed", outcome, want) + } + }) + }) + } +} diff --git a/pluginkit/plugintest/lifecycle.go b/pluginkit/plugintest/lifecycle.go new file mode 100644 index 0000000..3559eb9 --- /dev/null +++ b/pluginkit/plugintest/lifecycle.go @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: Apache-2.0 + +package plugintest + +import ( + "context" + "fmt" + "net/http" + "time" + + "github.com/gopherium/framework/pluginkit" + "github.com/gopherium/framework/pluginkit/internal/anyvalue" +) + +const ( + // fixRegisterFailure is the fix of a Register that answered an error or panicked. + fixRegisterFailure = "Return the plugin from Register with no error, and leave work that can fail to Start." + // fixNoPlugin is the fix of a Register that answered no plugin. + fixNoPlugin = "Return the plugin Register builds." + // fixRegisterTime is the fix of a Register that did not return within the step budget. + fixRegisterTime = "Keep Register to building the plugin, and open connections or read data in Start." + // fixRoutesBeforeStart is the fix of a Routes or a PublicPaths that broke its promise before Start. + fixRoutesBeforeStart = "Build the handler and the paths in Register, " + + "so Routes and PublicPaths answer whether or not Start ran." + // fixStopWithoutStart is the fix of a Stop that broke its promise on a plugin that never started. + fixStopWithoutStart = "Let Stop release only what Start opened, and return nil when Start never ran." + // fixStartStopAgain is the fix of a Start or a Stop that broke its promise in the Start, Stop, Start, Stop run. + fixStartStopAgain = "Let Start open again what Stop released, " + + "and let each call return by the time its context ends." +) + +// checks are the checks of the plugin contract in order, each run on a new plugin whose Register kept its promises. +var checks = []func(plugin pluginkit.Plugin, stepBudget time.Duration) []Finding{ + noFindingsPastRegister, routesBeforeStartFindings, stopWithoutStartFindings, startStopAgainFindings, +} + +// LifecycleFindings registers a new plugin from newDeps for each check and returns each promise the plugin breaks. +func LifecycleFindings[D any, P pluginkit.Plugin]( + registration pluginkit.Registration[D, P], newDeps func() D, stepBudget time.Duration, +) []Finding { + var findings []Finding + for _, check := range checks { + plugin, registerFinding := newPlugin(registration, newDeps(), stepBudget) + if registerFinding != nil { + return append(findings, *registerFinding) + } + findings = append(findings, check(plugin, stepBudget)...) + } + return findings +} + +// registerAnswer is what one Register answered: the plugin, nil when it answered none, and the id it calls itself. +type registerAnswer struct { + plugin pluginkit.Plugin + id string +} + +// newPlugin registers a new plugin from deps, answering it, or the finding of the first promise its Register broke. +func newPlugin[D any, P pluginkit.Plugin]( + registration pluginkit.Registration[D, P], deps D, stepBudget time.Duration, +) (pluginkit.Plugin, *Finding) { + outcome := outcomeOf("Register", stepBudget, registerCall(registration.Register, deps)) + return outcome.answer.plugin, registerFindingOf(outcome, registration.ID) +} + +// registerCall returns the call that registers a plugin from deps and reads the id that plugin calls itself. +func registerCall[D any, P pluginkit.Plugin]( + register func(D) (P, error), deps D, +) func(context.Context) (registerAnswer, error) { + return func(context.Context) (registerAnswer, error) { + plugin, err := register(deps) + if err != nil { + return registerAnswer{}, err + } + if anyvalue.IsNil(plugin) { + return registerAnswer{}, nil + } + return registerAnswer{plugin: plugin, id: plugin.ID()}, nil + } +} + +// registerFindingOf returns the finding of the first promise a Register with outcome broke, or nil when it kept each. +func registerFindingOf(outcome callOutcome[registerAnswer], manifestID string) *Finding { + switch { + case outcome.isOverBudget: + return &Finding{Rule: RuleRegisterTime, Problem: outcome.problem, Fix: fixRegisterTime} + case outcome.problem != "": + return &Finding{Rule: RuleRegister, Problem: outcome.problem, Fix: fixRegisterFailure} + case outcome.answer.plugin == nil: + return &Finding{Rule: RuleRegister, Problem: "Register answered no plugin", Fix: fixNoPlugin} + case outcome.answer.id != manifestID: + return &Finding{ + Rule: RuleRegister, + Problem: fmt.Sprintf("Register answered a plugin that calls itself %q, not %q", outcome.answer.id, manifestID), + Fix: fmt.Sprintf("Make ID return %q, the id in plugin.json.", manifestID), + } + default: + return nil + } +} + +// noFindingsPastRegister is the part of the register check after Register, and answers no finding. +func noFindingsPastRegister(pluginkit.Plugin, time.Duration) []Finding { + return nil +} + +// routesBeforeStartFindings returns a finding for each of Routes and PublicPaths that breaks its promise before Start. +func routesBeforeStartFindings(plugin pluginkit.Plugin, stepBudget time.Duration) []Finding { + var routesProblem, publicPathsProblem string + if provider, ok := plugin.(pluginkit.RouteProvider); ok { + routesProblem = routesBeforeStartProblem(provider, stepBudget) + } + if provider, ok := plugin.(pluginkit.PublicPathProvider); ok { + publicPathsProblem = publicPathsBeforeStartProblem(provider, stepBudget) + } + return findingsOf(RuleRoutesBeforeStart, fixRoutesBeforeStart, routesProblem, publicPathsProblem) +} + +// routesBeforeStartProblem calls Routes before any Start and returns the promise it broke, or "". +func routesBeforeStartProblem(provider pluginkit.RouteProvider, stepBudget time.Duration) string { + outcome := outcomeOf("Routes before Start", stepBudget, func(context.Context) (http.Handler, error) { + return provider.Routes(), nil + }) + if outcome.problem != "" { + return outcome.problem + } + if anyvalue.IsNil(outcome.answer) { + return "Routes before Start answered no handler" + } + return "" +} + +// publicPathsBeforeStartProblem calls PublicPaths before any Start and returns the promise it broke, or "". +func publicPathsBeforeStartProblem(provider pluginkit.PublicPathProvider, stepBudget time.Duration) string { + return outcomeOf("PublicPaths before Start", stepBudget, func(context.Context) ([]string, error) { + return provider.PublicPaths(), nil + }).problem +} + +// stopWithoutStartFindings returns the finding of a Stop that breaks its promise on a plugin that never started. +func stopWithoutStartFindings(plugin pluginkit.Plugin, stepBudget time.Duration) []Finding { + stopCall := lifecycleCall{name: "Stop before any Start", method: plugin.Stop} + return findingsOf(RuleStopWithoutStart, fixStopWithoutStart, stopCall.problem(stepBudget)) +} + +// startStopAgainFindings starts, stops, starts and stops a plugin, returning the finding of the first call that fails. +func startStopAgainFindings(plugin pluginkit.Plugin, stepBudget time.Duration) []Finding { + calls := []lifecycleCall{ + {name: "the first Start", method: plugin.Start}, + {name: "the first Stop", method: plugin.Stop}, + {name: "the second Start", method: plugin.Start}, + {name: "the second Stop", method: plugin.Stop}, + } + for _, call := range calls { + if problem := call.problem(stepBudget); problem != "" { + return findingsOf(RuleStartStopAgain, fixStartStopAgain, problem) + } + } + return nil +} + +// lifecycleCall is one Start or Stop a check makes, with the name its problem gives it. +type lifecycleCall struct { + name string + method func(ctx context.Context) error +} + +// problem calls the Start or Stop with a context that ends at stepBudget and returns the promise it broke, or "". +func (c lifecycleCall) problem(stepBudget time.Duration) string { + return outcomeOf(c.name, stepBudget, func(ctx context.Context) (struct{}, error) { + return struct{}{}, c.method(ctx) + }).problem +} + +// findingsOf returns a finding under rule with fix for each problem that is not empty, in order. +func findingsOf(rule, fix string, problems ...string) []Finding { + var findings []Finding + for _, problem := range problems { + if problem != "" { + findings = append(findings, Finding{Rule: rule, Problem: problem, Fix: fix}) + } + } + return findings +} diff --git a/pluginkit/plugintest/lifecycle_test.go b/pluginkit/plugintest/lifecycle_test.go new file mode 100644 index 0000000..21724e2 --- /dev/null +++ b/pluginkit/plugintest/lifecycle_test.go @@ -0,0 +1,778 @@ +// SPDX-License-Identifier: Apache-2.0 + +package plugintest_test + +import ( + "context" + "errors" + "fmt" + "maps" + "net/http" + "slices" + "sync" + "testing" + "testing/synctest" + "time" + + "github.com/gopherium/framework/pluginkit" + "github.com/gopherium/framework/pluginkit/plugintest" +) + +// stepBudget is the time limit the tests hand the checks. +const stepBudget = 50 * time.Millisecond + +const ( + // registerName is the name the checks give a Register. + registerName = "Register" + // idName is the name of the ID call on the plugin a Register answered. + idName = "ID" + // routesName is the name the checks give the Routes of a plugin that never started. + routesName = "Routes before Start" + // publicPathsName is the name the checks give the PublicPaths of a plugin that never started. + publicPathsName = "PublicPaths before Start" + // stopBeforeStartName is the name the checks give a Stop with no Start before it. + stopBeforeStartName = "Stop before any Start" + // firstStartName is the name the checks give the first Start of the Start, Stop, Start, Stop run. + firstStartName = "the first Start" + // firstStopName is the name the checks give the Stop after the first Start. + firstStopName = "the first Stop" + // secondStartName is the name the checks give the Start after the first Stop. + secondStartName = "the second Start" + // secondStopName is the name the checks give the Stop after the second Start. + secondStopName = "the second Stop" +) + +// fault is how one call of a fake plugin breaks its promise, its zero value a call that keeps it. +type fault struct { + // err is the error the call answers. + err error + // panicValue is what the call panics with, unless it is nil. + panicValue any + // neverReturns makes the call wait for the release of the test's calls. + neverReturns bool + // answersNil makes a Register answer no plugin, a Routes no handler and a PublicPaths no paths. + answersNil bool +} + +// fakeDeps is what one newDeps call built, numbered in the order of the calls. +type fakeDeps struct { + callNumber int +} + +// contextRecord is the context one Start or Stop received, with the name the checks give the call and its time. +type contextRecord struct { + name string + callTime time.Time + ctx context.Context +} + +// fakePluginFactory builds one test's fake plugins and records each call the checks make. +type fakePluginFactory struct { + // id is the id each plugin calls itself. + id string + // offersRoutes makes each plugin offer Routes and PublicPaths. + offersRoutes bool + // faults are the faults of the calls, by the names the checks give them. + faults map[string]fault + // release ends the wait of every call that never returns. + release chan struct{} + releaseOnce sync.Once + + mu sync.Mutex + newDepsCalls int + calls []string + contexts []contextRecord +} + +// newFakePluginFactory returns a factory of plugins "events" that offer routes and keep every promise. +func newFakePluginFactory(t *testing.T) *fakePluginFactory { + factory := &fakePluginFactory{ + id: "events", offersRoutes: true, faults: map[string]fault{}, release: make(chan struct{}), + } + t.Cleanup(factory.releaseCalls) + return factory +} + +// registration returns the registration of the plugin "events", whose Register builds a fake plugin. +func (f *fakePluginFactory) registration() pluginkit.Registration[fakeDeps, pluginkit.Plugin] { + return pluginkit.Registration[fakeDeps, pluginkit.Plugin]{ID: "events", Register: f.register} +} + +// lifecycleFindings checks the lifecycle of the factory's plugins with stepBudget. +func (f *fakePluginFactory) lifecycleFindings() []plugintest.Finding { + return plugintest.LifecycleFindings(f.registration(), f.newDeps, stepBudget) +} + +// newDeps returns the deps of one more newDeps call, numbered after the calls before it. +func (f *fakePluginFactory) newDeps() fakeDeps { + f.mu.Lock() + defer f.mu.Unlock() + f.newDepsCalls++ + f.calls = append(f.calls, fmt.Sprintf("newDeps %d", f.newDepsCalls)) + return fakeDeps{callNumber: f.newDepsCalls} +} + +// register records the deps it received, applies its fault and builds a fake plugin numbered by those deps. +func (f *fakePluginFactory) register(deps fakeDeps) (pluginkit.Plugin, error) { + f.record(fmt.Sprintf("Register of deps %d", deps.callNumber)) + registerFault := f.applyFault(registerName) + if registerFault.err != nil { + return nil, registerFault.err + } + if registerFault.answersNil { + return nil, nil + } + plugin := &fakePlugin{factory: f, depsNumber: deps.callNumber} + if f.offersRoutes { + return fakeRoutesPlugin{plugin}, nil + } + return plugin, nil +} + +// applyFault panics or waits as the fault of the call named name says, then returns that fault for the rest of it. +func (f *fakePluginFactory) applyFault(name string) fault { + callFault := f.faults[name] + if callFault.panicValue != nil { + panic(callFault.panicValue) + } + if callFault.neverReturns { + <-f.release + f.record(name + " returned after the release") + } + return callFault +} + +// record notes one call the checks made. +func (f *fakePluginFactory) record(call string) { + f.mu.Lock() + defer f.mu.Unlock() + f.calls = append(f.calls, call) +} + +// recordContext notes the context the Start or Stop named name received, and the time of the call. +func (f *fakePluginFactory) recordContext(ctx context.Context, name string) { + f.mu.Lock() + defer f.mu.Unlock() + f.contexts = append(f.contexts, contextRecord{name: name, callTime: time.Now(), ctx: ctx}) +} + +// recordedCalls returns the calls the checks made so far, in order. +func (f *fakePluginFactory) recordedCalls() []string { + f.mu.Lock() + defer f.mu.Unlock() + return slices.Clone(f.calls) +} + +// recordedContexts returns the context each Start and Stop received so far, in order. +func (f *fakePluginFactory) recordedContexts() []contextRecord { + f.mu.Lock() + defer f.mu.Unlock() + return slices.Clone(f.contexts) +} + +// releaseCalls ends the wait of every call that never returns, the first time it runs. +func (f *fakePluginFactory) releaseCalls() { + f.releaseOnce.Do(func() { close(f.release) }) +} + +// fakePlugin is one plugin a test's Register built, numbered by its deps and naming each Start and Stop it receives. +type fakePlugin struct { + factory *fakePluginFactory + depsNumber int + + mu sync.Mutex + startCount int +} + +// ID returns the id the factory's plugins call themselves, once its fault is applied. +func (p *fakePlugin) ID() string { + p.factory.applyFault(idName) + return p.factory.id +} + +// Start answers as the fault of the first or the second Start of this plugin says. +func (p *fakePlugin) Start(ctx context.Context) error { + return p.answerLifecycleCall(ctx, p.startName()) +} + +// Stop answers as the fault of the Stop after the Starts of this plugin so far says. +func (p *fakePlugin) Stop(ctx context.Context) error { + return p.answerLifecycleCall(ctx, p.stopName()) +} + +// startName returns the name the checks give this plugin's next Start, counting it. +func (p *fakePlugin) startName() string { + p.mu.Lock() + defer p.mu.Unlock() + p.startCount++ + return [...]string{1: firstStartName, 2: secondStartName}[p.startCount] +} + +// stopName returns the name the checks give a Stop of this plugin after its Starts so far. +func (p *fakePlugin) stopName() string { + p.mu.Lock() + defer p.mu.Unlock() + return [...]string{stopBeforeStartName, firstStopName, secondStopName}[p.startCount] +} + +// answerLifecycleCall records the Start or Stop named name and its context, then answers the error of its fault. +func (p *fakePlugin) answerLifecycleCall(ctx context.Context, name string) error { + p.recordCall(name) + p.factory.recordContext(ctx, name) + return p.factory.applyFault(name).err +} + +// recordCall notes the call named name of this plugin. +func (p *fakePlugin) recordCall(name string) { + p.factory.record(fmt.Sprintf("%s of plugin %d", name, p.depsNumber)) +} + +// fakeRoutesPlugin is a fake plugin that also offers Routes and PublicPaths. +type fakeRoutesPlugin struct { + *fakePlugin +} + +// Routes records its call and answers a handler, unless its fault breaks the promise. +func (p fakeRoutesPlugin) Routes() http.Handler { + p.recordCall(routesName) + if p.factory.applyFault(routesName).answersNil { + return nil + } + return http.NotFoundHandler() +} + +// PublicPaths records its call and answers one path, unless its fault says otherwise. +func (p fakeRoutesPlugin) PublicPaths() []string { + p.recordCall(publicPathsName) + if p.factory.applyFault(publicPathsName).answersNil { + return nil + } + return []string{"/feed.xml"} +} + +// valuePlugin is a plugin held by value that keeps every promise. +type valuePlugin struct{} + +// ID returns the id of the registration that builds it. +func (valuePlugin) ID() string { + return "events" +} + +// Start starts nothing. +func (valuePlugin) Start(context.Context) error { + return nil +} + +// Stop stops nothing. +func (valuePlugin) Stop(context.Context) error { + return nil +} + +// handlerPlugin is a plugin held by value that keeps every promise and answers its handler from Routes. +type handlerPlugin struct { + valuePlugin + handler http.Handler +} + +// Routes answers the plugin's handler. +func (p handlerPlugin) Routes() http.Handler { + return p.handler +} + +// mapHandler is a handler whose type is a map. +type mapHandler map[string]string + +// ServeHTTP answers nothing. +func (mapHandler) ServeHTTP(http.ResponseWriter, *http.Request) {} + +// sliceHandler is a handler whose type is a slice. +type sliceHandler []string + +// ServeHTTP answers nothing. +func (sliceHandler) ServeHTTP(http.ResponseWriter, *http.Request) {} + +// chanHandler is a handler whose type is a channel. +type chanHandler chan string + +// ServeHTTP answers nothing. +func (chanHandler) ServeHTTP(http.ResponseWriter, *http.Request) {} + +// runWithFakePluginFactory runs test on a new fake plugin factory inside a synctest bubble with its own fake clock. +func runWithFakePluginFactory(t *testing.T, test func(t *testing.T, factory *fakePluginFactory)) { + t.Helper() + synctest.Test(t, func(t *testing.T) { + test(t, newFakePluginFactory(t)) + }) +} + +// finding returns the finding under rule with problem and fix. +func finding(rule, problem, fix string) plugintest.Finding { + return plugintest.Finding{Rule: rule, Problem: problem, Fix: fix} +} + +// registerFailureFinding returns the register finding of a Register that answered an error or panicked with problem. +func registerFailureFinding(problem string) plugintest.Finding { + return finding("register", problem, + "Return the plugin from Register with no error, and leave work that can fail to Start.") +} + +// registerTimeFinding returns the register-time finding of a Register that did not return within the budget. +func registerTimeFinding() plugintest.Finding { + return finding("register-time", "Register did not return within 50ms", + "Keep Register to building the plugin, and open connections or read data in Start.") +} + +// noPluginFinding returns the register finding of a Register that answered no plugin. +func noPluginFinding() plugintest.Finding { + return finding("register", "Register answered no plugin", "Return the plugin Register builds.") +} + +// routesFinding returns the routes-before-start finding with problem. +func routesFinding(problem string) plugintest.Finding { + return finding("routes-before-start", problem, + "Build the handler and the paths in Register, so Routes and PublicPaths answer whether or not Start ran.") +} + +// stopWithoutStartFinding returns the stop-without-start finding with problem. +func stopWithoutStartFinding(problem string) plugintest.Finding { + return finding("stop-without-start", problem, + "Let Stop release only what Start opened, and return nil when Start never ran.") +} + +// startStopAgainFinding returns the start-stop-again finding with problem. +func startStopAgainFinding(problem string) plugintest.Finding { + return finding("start-stop-again", problem, + "Let Start open again what Stop released, and let each call return by the time its context ends.") +} + +// wantFindings checks that got holds exactly want, in order. +func wantFindings(t *testing.T, got, want []plugintest.Finding) { + t.Helper() + if !slices.Equal(got, want) { + t.Errorf("findings = %+v\nwant %+v", got, want) + } +} + +// wantCalls checks that the checks made exactly want of the factory's plugins so far, in order. +func wantCalls(t *testing.T, factory *fakePluginFactory, want []string) { + t.Helper() + if got := factory.recordedCalls(); !slices.Equal(got, want) { + t.Errorf("calls = %q\nwant %q", got, want) + } +} + +// everyCall is each call the checks make of plugins that keep every promise, in order. +var everyCall = []string{ + "newDeps 1", "Register of deps 1", + "newDeps 2", "Register of deps 2", "Routes before Start of plugin 2", "PublicPaths before Start of plugin 2", + "newDeps 3", "Register of deps 3", "Stop before any Start of plugin 3", + "newDeps 4", "Register of deps 4", "the first Start of plugin 4", "the first Stop of plugin 4", + "the second Start of plugin 4", "the second Stop of plugin 4", +} + +func TestLifecycleFindingsAnswersNilForAPluginThatKeepsEveryPromise(t *testing.T) { + t.Parallel() + + tests := map[string]func(factory *fakePluginFactory) []plugintest.Finding{ + "a plugin with routes and public paths": func(factory *fakePluginFactory) []plugintest.Finding { + return factory.lifecycleFindings() + }, + "a plugin with no routes and no public paths": func(factory *fakePluginFactory) []plugintest.Finding { + factory.offersRoutes = false + return factory.lifecycleFindings() + }, + "a plugin whose public paths are nil": func(factory *fakePluginFactory) []plugintest.Finding { + factory.faults[publicPathsName] = fault{answersNil: true} + return factory.lifecycleFindings() + }, + "a plugin held by a pointer to its own type": func(factory *fakePluginFactory) []plugintest.Finding { + registration := pluginkit.Registration[fakeDeps, *fakePlugin]{ + ID: "events", + Register: func(deps fakeDeps) (*fakePlugin, error) { + return &fakePlugin{factory: factory, depsNumber: deps.callNumber}, nil + }, + } + return plugintest.LifecycleFindings(registration, factory.newDeps, stepBudget) + }, + "a plugin held by value": func(factory *fakePluginFactory) []plugintest.Finding { + registration := pluginkit.Registration[fakeDeps, valuePlugin]{ + ID: "events", + Register: func(fakeDeps) (valuePlugin, error) { return valuePlugin{}, nil }, + } + return plugintest.LifecycleFindings(registration, factory.newDeps, stepBudget) + }, + } + for name, lifecycleFindings := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + runWithFakePluginFactory(t, func(t *testing.T, factory *fakePluginFactory) { + if findings := lifecycleFindings(factory); findings != nil { + t.Errorf("findings = %+v, want nil", findings) + } + }) + }) + } +} + +func TestLifecycleFindingsGivesOnlyTheFindingOfARegisterThatBreaksAPromise(t *testing.T) { + t.Parallel() + + tests := map[string]struct { + breakPromise func(factory *fakePluginFactory) + want plugintest.Finding + }{ + "an error": { + func(factory *fakePluginFactory) { factory.faults[registerName] = fault{err: errors.New("no database")} }, + registerFailureFinding("Register answered the error: no database"), + }, + "a panic": { + func(factory *fakePluginFactory) { factory.faults[registerName] = fault{panicValue: "boom"} }, + registerFailureFinding("Register panicked: boom"), + }, + "a panic in the ID of what it answered": { + func(factory *fakePluginFactory) { factory.faults[idName] = fault{panicValue: "no id"} }, + registerFailureFinding("Register panicked: no id"), + }, + "no plugin": { + func(factory *fakePluginFactory) { factory.faults[registerName] = fault{answersNil: true} }, + noPluginFinding(), + }, + "a plugin that calls itself by another id": { + func(factory *fakePluginFactory) { factory.id = "news" }, + finding("register", `Register answered a plugin that calls itself "news", not "events"`, + `Make ID return "events", the id in plugin.json.`), + }, + "a plugin that calls itself by no id": { + func(factory *fakePluginFactory) { factory.id = "" }, + finding("register", `Register answered a plugin that calls itself "", not "events"`, + `Make ID return "events", the id in plugin.json.`), + }, + "no return": { + func(factory *fakePluginFactory) { factory.faults[registerName] = fault{neverReturns: true} }, + registerTimeFinding(), + }, + "no return from the ID of what it answered": { + func(factory *fakePluginFactory) { factory.faults[idName] = fault{neverReturns: true} }, + registerTimeFinding(), + }, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + runWithFakePluginFactory(t, func(t *testing.T, factory *fakePluginFactory) { + tc.breakPromise(factory) + + findings := factory.lifecycleFindings() + + wantFindings(t, findings, []plugintest.Finding{tc.want}) + wantCalls(t, factory, []string{"newDeps 1", "Register of deps 1"}) + }) + }) + } +} + +func TestLifecycleFindingsGivesNoPluginForANilPointerOfThePluginsOwnType(t *testing.T) { + t.Parallel() + + runWithFakePluginFactory(t, func(t *testing.T, factory *fakePluginFactory) { + registration := pluginkit.Registration[fakeDeps, *fakePlugin]{ + ID: "events", + Register: func(fakeDeps) (*fakePlugin, error) { return nil, nil }, + } + + findings := plugintest.LifecycleFindings(registration, factory.newDeps, stepBudget) + + wantFindings(t, findings, []plugintest.Finding{noPluginFinding()}) + wantCalls(t, factory, []string{"newDeps 1"}) + }) +} + +// callCase is one way a call after Register breaks its promise, with the one finding it gives. +type callCase struct { + callName string + callFault fault + want plugintest.Finding +} + +// panicAndNoReturnCases returns the cases of callName panicking and never returning, with their findings. +func panicAndNoReturnCases(callName string, findingOf func(problem string) plugintest.Finding) map[string]callCase { + return map[string]callCase{ + callName + " panics": {callName, fault{panicValue: "boom"}, findingOf(callName + " panicked: boom")}, + callName + " never returns": { + callName, fault{neverReturns: true}, findingOf(callName + " did not return within 50ms"), + }, + } +} + +// failureCases returns the cases of callName answering an error, panicking and never returning, with their findings. +func failureCases(callName string, findingOf func(problem string) plugintest.Finding) map[string]callCase { + cases := panicAndNoReturnCases(callName, findingOf) + cases[callName+" answers an error"] = callCase{ + callName, fault{err: errors.New("not ready")}, findingOf(callName + " answered the error: not ready"), + } + return cases +} + +// wantOneFindingForEachCase checks that the fault of each case, alone, gives the case's finding alone. +func wantOneFindingForEachCase(t *testing.T, cases map[string]callCase) { + t.Helper() + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + t.Parallel() + + runWithFakePluginFactory(t, func(t *testing.T, factory *fakePluginFactory) { + factory.faults[tc.callName] = tc.callFault + + findings := factory.lifecycleFindings() + + wantFindings(t, findings, []plugintest.Finding{tc.want}) + }) + }) + } +} + +func TestLifecycleFindingsNamesABrokenPromiseOfRoutesOrPublicPathsBeforeStartUnderItsRule(t *testing.T) { + t.Parallel() + + cases := map[string]callCase{ + "Routes answers no handler": { + routesName, fault{answersNil: true}, routesFinding("Routes before Start answered no handler"), + }, + } + maps.Copy(cases, panicAndNoReturnCases(routesName, routesFinding)) + maps.Copy(cases, panicAndNoReturnCases(publicPathsName, routesFinding)) + wantOneFindingForEachCase(t, cases) +} + +func TestLifecycleFindingsNamesABrokenPromiseOfAStopBeforeAnyStartUnderItsRule(t *testing.T) { + t.Parallel() + + wantOneFindingForEachCase(t, failureCases(stopBeforeStartName, stopWithoutStartFinding)) +} + +func TestLifecycleFindingsNamesABrokenPromiseOfEachStartAndStopOfTheRunUnderItsRule(t *testing.T) { + t.Parallel() + + cases := map[string]callCase{} + for _, callName := range []string{firstStartName, firstStopName, secondStartName, secondStopName} { + maps.Copy(cases, failureCases(callName, startStopAgainFinding)) + } + wantOneFindingForEachCase(t, cases) +} + +func TestLifecycleFindingsGivesNoHandlerForARoutesThatAnswersANilFunctionMapSliceOrChannel(t *testing.T) { + t.Parallel() + + tests := map[string]http.Handler{ + "a nil function": http.HandlerFunc(nil), + "a nil map": mapHandler(nil), + "a nil slice": sliceHandler(nil), + "a nil channel": chanHandler(nil), + } + for name, handler := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + runWithFakePluginFactory(t, func(t *testing.T, factory *fakePluginFactory) { + registration := pluginkit.Registration[fakeDeps, handlerPlugin]{ + ID: "events", + Register: func(fakeDeps) (handlerPlugin, error) { return handlerPlugin{handler: handler}, nil }, + } + + findings := plugintest.LifecycleFindings(registration, factory.newDeps, stepBudget) + + wantFindings(t, findings, []plugintest.Finding{routesFinding("Routes before Start answered no handler")}) + }) + }) + } +} + +func TestLifecycleFindingsRunsEachCheckOnAPluginOfItsOwnFromDepsOfItsOwn(t *testing.T) { + t.Parallel() + + tests := map[string]struct { + breakPromise func(factory *fakePluginFactory) + want []string + }{ + "a plugin that keeps every promise": {func(*fakePluginFactory) {}, everyCall}, + "a plugin whose Routes never returns": { + func(factory *fakePluginFactory) { factory.faults[routesName] = fault{neverReturns: true} }, everyCall, + }, + "a plugin whose first Stop answers an error": { + func(factory *fakePluginFactory) { + factory.faults[firstStopName] = fault{err: errors.New("already closed")} + }, + everyCall[:len(everyCall)-2], + }, + "a plugin whose first Start panics": { + func(factory *fakePluginFactory) { factory.faults[firstStartName] = fault{panicValue: "boom"} }, + everyCall[:len(everyCall)-3], + }, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + runWithFakePluginFactory(t, func(t *testing.T, factory *fakePluginFactory) { + tc.breakPromise(factory) + + factory.lifecycleFindings() + + wantCalls(t, factory, tc.want) + }) + }) + } +} + +func TestLifecycleFindingsKeepsOneBrokenPromiseFromHidingAnother(t *testing.T) { + t.Parallel() + + runWithFakePluginFactory(t, func(t *testing.T, factory *fakePluginFactory) { + factory.faults[routesName] = fault{answersNil: true} + factory.faults[publicPathsName] = fault{panicValue: "boom"} + factory.faults[stopBeforeStartName] = fault{err: errors.New("nothing to close")} + factory.faults[secondStartName] = fault{err: errors.New("already started")} + + findings := factory.lifecycleFindings() + + wantFindings(t, findings, []plugintest.Finding{ + routesFinding("Routes before Start answered no handler"), + routesFinding("PublicPaths before Start panicked: boom"), + stopWithoutStartFinding("Stop before any Start answered the error: nothing to close"), + startStopAgainFinding("the second Start answered the error: already started"), + }) + }) +} + +func TestLifecycleFindingsCutsACallThatNeverReturnsAtTheStepBudgetAndRunsTheLaterChecks(t *testing.T) { + t.Parallel() + + runWithFakePluginFactory(t, func(t *testing.T, factory *fakePluginFactory) { + factory.faults[routesName] = fault{neverReturns: true} + factory.faults[firstStartName] = fault{neverReturns: true} + callTime := time.Now() + + findings := factory.lifecycleFindings() + + if waitTime := time.Since(callTime); waitTime != 2*stepBudget { + t.Errorf("the checks took %v, want two step budgets of %v", waitTime, stepBudget) + } + wantFindings(t, findings, []plugintest.Finding{ + routesFinding("Routes before Start did not return within 50ms"), + startStopAgainFinding("the first Start did not return within 50ms"), + }) + wantCalls(t, factory, everyCall[:len(everyCall)-3]) + }) +} + +func TestLifecycleFindingsNeverBlocksACallThatReturnsAfterItsCheckEnded(t *testing.T) { + t.Parallel() + + runWithFakePluginFactory(t, func(t *testing.T, factory *fakePluginFactory) { + factory.faults[firstStartName] = fault{neverReturns: true} + findings := factory.lifecycleFindings() + + factory.releaseCalls() + synctest.Wait() + + wantFindings(t, findings, []plugintest.Finding{ + startStopAgainFinding("the first Start did not return within 50ms"), + }) + wantCalls(t, factory, + append(slices.Clone(everyCall[:len(everyCall)-3]), "the first Start returned after the release")) + }) +} + +func TestLifecycleFindingsHandsEachStartAndStopAContextOfItsOwnThatEndsAtTheStepBudget(t *testing.T) { + t.Parallel() + + runWithFakePluginFactory(t, func(t *testing.T, factory *fakePluginFactory) { + factory.lifecycleFindings() + + records := factory.recordedContexts() + names := []string{} + for i, record := range records { + names = append(names, record.name) + wantBudgetContext(t, record) + for _, earlierRecord := range records[:i] { + if earlierRecord.ctx == record.ctx { + t.Errorf("%s got the context of %s, want one of its own", record.name, earlierRecord.name) + } + } + } + if want := []string{ + stopBeforeStartName, firstStartName, firstStopName, secondStartName, secondStopName, + }; !slices.Equal(names, want) { + t.Errorf("calls with a context = %q, want %q", names, want) + } + }) +} + +// wantBudgetContext checks that record's context ends within stepBudget of its call and was cancelled once it returned. +func wantBudgetContext(t *testing.T, record contextRecord) { + t.Helper() + deadline, hasDeadline := record.ctx.Deadline() + if !hasDeadline { + t.Errorf("%s got a context with no deadline, want one at the step budget", record.name) + } + if deadline.After(record.callTime.Add(stepBudget)) { + t.Errorf("%s got a context ending at %v, want no later than %v", record.name, deadline, + record.callTime.Add(stepBudget)) + } + if !deadline.After(record.callTime) { + t.Errorf("%s got a context that ended at %v, before its call at %v", record.name, deadline, record.callTime) + } + if err := record.ctx.Err(); !errors.Is(err, context.Canceled) { + t.Errorf("%s's context ended with %v, want it cancelled once the call returned", record.name, err) + } +} + +func TestLifecycleFindingsEndsAtARegisterThatBreaksAPromiseForALaterCheck(t *testing.T) { + t.Parallel() + + runWithFakePluginFactory(t, func(t *testing.T, factory *fakePluginFactory) { + factory.faults[routesName] = fault{answersNil: true} + registration := pluginkit.Registration[fakeDeps, pluginkit.Plugin]{ + ID: "events", + Register: func(deps fakeDeps) (pluginkit.Plugin, error) { + if deps.callNumber == 3 { + return nil, errors.New("no database") + } + return factory.register(deps) + }, + } + + findings := plugintest.LifecycleFindings(registration, factory.newDeps, stepBudget) + + wantFindings(t, findings, []plugintest.Finding{ + routesFinding("Routes before Start answered no handler"), + registerFailureFinding("Register answered the error: no database"), + }) + wantCalls(t, factory, everyCall[:7]) + }) +} + +func TestLifecycleFindingsLetsAPanicWhileBuildingDepsReachTheCaller(t *testing.T) { + t.Parallel() + + runWithFakePluginFactory(t, func(t *testing.T, factory *fakePluginFactory) { + newDeps := func() fakeDeps { + deps := factory.newDeps() + if deps.callNumber == 2 { + panic("no settings for events") + } + return deps + } + + defer func() { + if got := recover(); got != "no settings for events" { + t.Errorf("the panic = %v, want the one newDeps raised", got) + } + wantCalls(t, factory, everyCall[:3]) + }() + plugintest.LifecycleFindings(factory.registration(), newDeps, stepBudget) + t.Error("LifecycleFindings returned, want the panic of newDeps to reach the caller") + }) +} diff --git a/pluginkit/plugintest/plugintest.go b/pluginkit/plugintest/plugintest.go new file mode 100644 index 0000000..c94e084 --- /dev/null +++ b/pluginkit/plugintest/plugintest.go @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package plugintest checks the promises a plugin makes to its host, from the plugin's own tests. +package plugintest + +// Finding is one promise a plugin breaks: the rule it falls under, what is wrong and how to fix it. +type Finding struct { + Rule string + Problem string + Fix string +} + +const ( + // RuleRegister is the rule that Register answers a plugin, with no error and no panic, whose ID is the manifest id. + RuleRegister = "register" + // RuleRegisterTime is the rule that Register returns within the step budget. + RuleRegisterTime = "register-time" + // RuleRoutesBeforeStart is the rule that Routes answers a handler and PublicPaths answers, both before Start runs. + RuleRoutesBeforeStart = "routes-before-start" + // RuleStopWithoutStart is the rule that Stop returns nil, with no panic, on a plugin that never started. + RuleStopWithoutStart = "stop-without-start" + // RuleStartStopAgain is the rule that Start, Stop, Start and Stop each return nil within the step budget. + RuleStartStopAgain = "start-stop-again" +) From ed1df3ef505b112f64f9e65897260e9183d90af0 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 29 Nov 2026 19:12:57 +0100 Subject: [PATCH 05/11] test(pluginkit): run the plugin check scenarios --- pluginkit/features/features_test.go | 4 + .../features/steps_plugin_checks_test.go | 473 ++++++++++++++++++ 2 files changed, 477 insertions(+) create mode 100644 pluginkit/features/steps_plugin_checks_test.go diff --git a/pluginkit/features/features_test.go b/pluginkit/features/features_test.go index 23abd25..55ce28e 100644 --- a/pluginkit/features/features_test.go +++ b/pluginkit/features/features_test.go @@ -77,3 +77,7 @@ func TestSettingsChanges(t *testing.T) { func TestScreenGate(t *testing.T) { runFeature(t, "screen-gate.feature", initializeScreenGate(t)) } + +func TestPluginChecks(t *testing.T) { + runFeature(t, "plugin-checks.feature", initializePluginChecks()) +} diff --git a/pluginkit/features/steps_plugin_checks_test.go b/pluginkit/features/steps_plugin_checks_test.go new file mode 100644 index 0000000..e6bdb4a --- /dev/null +++ b/pluginkit/features/steps_plugin_checks_test.go @@ -0,0 +1,473 @@ +// SPDX-License-Identifier: Apache-2.0 + +package features_test + +import ( + "cmp" + "context" + "errors" + "fmt" + "net/http" + "slices" + "sync" + "time" + + "github.com/cucumber/godog" + + "github.com/gopherium/framework/pluginkit" + "github.com/gopherium/framework/pluginkit/plugintest" + "github.com/gopherium/framework/pluginkit/wire" +) + +// errorCallsPattern matches the words a step names each call of the fake plugin by that can answer an error. +const errorCallsPattern = `Register|Stop before any Start|the first Start|the Stop after the first Start|` + + `the second Start|the Stop after the second Start` + +// callsPattern matches the words a step names each call of the fake plugin by. +const callsPattern = `Routes|PublicPaths|` + errorCallsPattern + +// startCallNames names each Start of a fake plugin by the count of Starts before it. +var startCallNames = []string{"the first Start", "the second Start"} + +// stopCallNames names each Stop of a fake plugin by the count of Starts before it. +var stopCallNames = []string{ + "Stop before any Start", "the Stop after the first Start", "the Stop after the second Start", +} + +// firstCallOfEachCheck names the first call each check makes of the plugin it registers, none for the register check. +var firstCallOfEachCheck = []string{"", "Routes", "Stop before any Start", "the first Start"} + +// fakeDeps is what a plugin checks scenario lends each Register: the count of dependencies built, this one included. +type fakeDeps struct{ buildNumber int } + +// startStopCall is one Start or Stop a fake plugin ran: the method, when it ran and when the context it got ends. +type startStopCall struct { + method string + calledAt time.Time + deadline time.Time + hasDeadline bool +} + +// pluginChecksWorld is what one scenario of the plugin checks feature fakes, records and finds. +type pluginChecksWorld struct { + mu sync.Mutex + endOfScenario chan struct{} + pluginID string + claimedID string + hasRoutes bool + answersNoPlugin bool + answersNoHandler bool + faults map[string]func() + callErrors map[string]error + builtDeps []fakeDeps + receivedDeps []fakeDeps + plugins []*fakePlugin + startStopCalls []startStopCall + findings []plugintest.Finding + manifest wire.Manifest + reservedIDs []string + idCheckErr error +} + +// fakePlugin is the plugin each Register of a plugin checks scenario builds, whose calls run the scenario's faults. +type fakePlugin struct { + world *pluginChecksWorld + id string + startCount int + firstCall string +} + +// ID returns the id the plugin calls itself. +func (p *fakePlugin) ID() string { + return p.id +} + +// Start notes the call and its context, then runs the fault of the first or the second Start and answers its error. +func (p *fakePlugin) Start(ctx context.Context) error { + call := p.startCallName() + p.noteFirstCall(call) + p.world.recordCall(ctx, "Start") + return p.world.answerCall(call) +} + +// Stop notes the call and its context, then runs the fault of this Stop and answers its error. +func (p *fakePlugin) Stop(ctx context.Context) error { + call := p.stopCallName() + p.noteFirstCall(call) + p.world.recordCall(ctx, "Stop") + return p.world.answerCall(call) +} + +// noteFirstCall notes the call these words name as the plugin's first call, unless it got one before. +func (p *fakePlugin) noteFirstCall(call string) { + p.world.mu.Lock() + defer p.world.mu.Unlock() + p.firstCall = cmp.Or(p.firstCall, call) +} + +// startCallName counts one more Start of the plugin and returns the words naming it. +func (p *fakePlugin) startCallName() string { + p.world.mu.Lock() + defer p.world.mu.Unlock() + name := startCallNames[p.startCount] + p.startCount++ + return name +} + +// stopCallName returns the words naming a Stop of the plugin after the Starts it ran. +func (p *fakePlugin) stopCallName() string { + p.world.mu.Lock() + defer p.world.mu.Unlock() + return stopCallNames[p.startCount] +} + +// fakePluginWithRoutes is a fake plugin with routes and public paths. +type fakePluginWithRoutes struct{ *fakePlugin } + +// Routes runs the scenario's fault for Routes, then answers a handler, or none when the scenario says so. +func (p fakePluginWithRoutes) Routes() http.Handler { + p.noteFirstCall("Routes") + p.world.runFault("Routes") + return p.world.routesHandler() +} + +// PublicPaths runs the scenario's fault for PublicPaths, then answers one public path. +func (p fakePluginWithRoutes) PublicPaths() []string { + p.noteFirstCall("PublicPaths") + p.world.runFault("PublicPaths") + return []string{"/health"} +} + +// recordCall notes that the Start or Stop method ran now with ctx, and when ctx ends. +func (w *pluginChecksWorld) recordCall(ctx context.Context, method string) { + deadline, hasDeadline := ctx.Deadline() + call := startStopCall{method: method, calledAt: time.Now(), deadline: deadline, hasDeadline: hasDeadline} + w.mu.Lock() + defer w.mu.Unlock() + w.startStopCalls = append(w.startStopCalls, call) +} + +// runFault runs the fault the scenario gives the call these words name, if it gives one. +func (w *pluginChecksWorld) runFault(call string) { + w.mu.Lock() + fault := w.faults[call] + w.mu.Unlock() + if fault != nil { + fault() + } +} + +// answerCall runs the fault the scenario gives the call these words name and returns the error it answers, or nil. +func (w *pluginChecksWorld) answerCall(call string) error { + w.runFault(call) + w.mu.Lock() + defer w.mu.Unlock() + return w.callErrors[call] +} + +// routesHandler returns the handler the fake plugin's Routes answers, or nil when the scenario says it answers none. +func (w *pluginChecksWorld) routesHandler() http.Handler { + w.mu.Lock() + defer w.mu.Unlock() + if w.answersNoHandler { + return nil + } + return http.NotFoundHandler() +} + +// register notes the deps it received, runs the scenario's fault for Register and answers a new fake plugin. +func (w *pluginChecksWorld) register(deps fakeDeps) (pluginkit.Plugin, error) { + w.mu.Lock() + w.receivedDeps = append(w.receivedDeps, deps) + w.mu.Unlock() + if err := w.answerCall("Register"); err != nil { + return nil, err + } + return w.newPlugin(), nil +} + +// newPlugin returns and notes a new fake plugin as the scenario describes it, or nil when Register answers no plugin. +func (w *pluginChecksWorld) newPlugin() pluginkit.Plugin { + w.mu.Lock() + defer w.mu.Unlock() + if w.answersNoPlugin { + return nil + } + plugin := &fakePlugin{world: w, id: cmp.Or(w.claimedID, w.pluginID)} + w.plugins = append(w.plugins, plugin) + if !w.hasRoutes { + return plugin + } + return fakePluginWithRoutes{plugin} +} + +// newDeps builds the dependencies of one more Register, noting each. +func (w *pluginChecksWorld) newDeps() fakeDeps { + w.mu.Lock() + defer w.mu.Unlock() + deps := fakeDeps{buildNumber: len(w.builtDeps) + 1} + w.builtDeps = append(w.builtDeps, deps) + return deps +} + +// keepEveryPromise names the fake plugin id, which keeps every promise no other step breaks. +func (w *pluginChecksWorld) keepEveryPromise(id string) { + w.pluginID = id +} + +// leaveOutRoutes names the fake plugin id and gives it no routes and no public paths. +func (w *pluginChecksWorld) leaveOutRoutes(id string) { + w.pluginID = id + w.hasRoutes = false +} + +// answerError names the fake plugin id and has the call these words name answer an error with text. +func (w *pluginChecksWorld) answerError(id, text, call string) { + w.pluginID = id + w.callErrors[call] = errors.New(text) +} + +// addFault names the fake plugin id and gives the call these words name the fault. +func (w *pluginChecksWorld) addFault(id, call string, fault func()) { + w.pluginID = id + w.faults[call] = fault +} + +// panicIn names the fake plugin id and has the call these words name panic with value. +func (w *pluginChecksWorld) panicIn(id, value, call string) { + w.addFault(id, call, func() { panic(value) }) +} + +// blockCall names the fake plugin id and has the call these words name return only when the scenario ends. +func (w *pluginChecksWorld) blockCall(id, call string) { + w.addFault(id, call, func() { <-w.endOfScenario }) +} + +// delayRegister names the fake plugin id and has its Register take the duration text, or less when the scenario ends. +func (w *pluginChecksWorld) delayRegister(id, text string) error { + delay, err := time.ParseDuration(text) + if err != nil { + return err + } + w.addFault(id, "Register", func() { + select { + case <-time.After(delay): + case <-w.endOfScenario: + } + }) + return nil +} + +// answerNoPlugin names the fake plugin id and has its Register answer no plugin and no error. +func (w *pluginChecksWorld) answerNoPlugin(id string) { + w.pluginID = id + w.answersNoPlugin = true +} + +// answerNoHandler names the fake plugin id and has its Routes answer no handler. +func (w *pluginChecksWorld) answerNoHandler(id string) { + w.pluginID = id + w.answersNoHandler = true +} + +// claimID names the fake plugin id and has its ID answer name in place of id. +func (w *pluginChecksWorld) claimID(id, name string) { + w.pluginID = id + w.claimedID = name +} + +// checkLifecycle checks the lifecycle of the plugin id with the time limit text, noting the findings. +func (w *pluginChecksWorld) checkLifecycle(id, text string) error { + stepBudget, err := time.ParseDuration(text) + if err != nil { + return err + } + registration := pluginkit.Registration[fakeDeps, pluginkit.Plugin]{ID: id, Register: w.register} + w.findings = plugintest.LifecycleFindings(registration, w.newDeps, stepBudget) + return nil +} + +// noFinding checks that the check gave no finding. +func (w *pluginChecksWorld) noFinding() error { + if len(w.findings) > 0 { + return fmt.Errorf("the check gives %+v, want no finding", w.findings) + } + return nil +} + +// oneFindingUnder checks that the check gave one finding, under rule. +func (w *pluginChecksWorld) oneFindingUnder(rule string) error { + if len(w.findings) != 1 || w.findings[0].Rule != rule { + return fmt.Errorf("the check gives %+v, want one finding under %q", w.findings, rule) + } + return nil +} + +// findingReads checks that the part, problem or fix, of the check's one finding reads want. +func (w *pluginChecksWorld) findingReads(part, want string) error { + if len(w.findings) != 1 { + return fmt.Errorf("the check gives %+v, want one finding", w.findings) + } + got := map[string]string{"problem": w.findings[0].Problem, "fix": w.findings[0].Fix}[part] + if got != want { + return fmt.Errorf("its %s reads %q, want %q", part, got, want) + } + return nil +} + +// findingsInOrder checks that the check gave one finding for each row of table, with its rule and problem, in order. +func (w *pluginChecksWorld) findingsInOrder(table *godog.Table) error { + columns := columnsOf(table) + var got, want [][2]string + for _, finding := range w.findings { + got = append(got, [2]string{finding.Rule, finding.Problem}) + } + for _, row := range table.Rows[1:] { + want = append(want, [2]string{row.Cells[columns["rule"]].Value, row.Cells[columns["problem"]].Value}) + } + if !slices.Equal(got, want) { + return fmt.Errorf("the check gives the rules and problems %q, want %q", got, want) + } + return nil +} + +// onePluginPerCheck checks that each check of id ran on its own plugin, from dependencies built for it alone. +func (w *pluginChecksWorld) onePluginPerCheck(id string) error { + w.mu.Lock() + defer w.mu.Unlock() + if len(w.builtDeps) != len(w.receivedDeps) { + return fmt.Errorf("dependencies were built %d times for %d Registers of %s", + len(w.builtDeps), len(w.receivedDeps), id) + } + if !slices.Equal(w.receivedDeps, w.builtDeps) { + return fmt.Errorf("the Registers of %s received %+v, want %+v", id, w.receivedDeps, w.builtDeps) + } + firstCalls := make([]string, 0, len(w.plugins)) + for _, plugin := range w.plugins { + firstCalls = append(firstCalls, plugin.firstCall) + } + if !slices.Equal(firstCalls, firstCallOfEachCheck) { + return fmt.Errorf("the plugins of %s got the first calls %q, want a plugin of its own for each check, getting %q", + id, firstCalls, firstCallOfEachCheck) + } + return nil +} + +// contextsEndWithin checks that each Start and Stop of the plugin id got a context that ends within text of the call. +func (w *pluginChecksWorld) contextsEndWithin(id, text string) error { + limit, err := time.ParseDuration(text) + if err != nil { + return err + } + w.mu.Lock() + defer w.mu.Unlock() + methodsThatRan := map[string]bool{} + for _, call := range w.startStopCalls { + if !call.hasDeadline { + return fmt.Errorf("a %s of %s got a context with no deadline", call.method, id) + } + if latestDeadline := call.calledAt.Add(limit); call.deadline.After(latestDeadline) { + return fmt.Errorf("a %s of %s got a context that ends at %v, want by %v", + call.method, id, call.deadline, latestDeadline) + } + methodsThatRan[call.method] = true + } + if !methodsThatRan["Start"] || !methodsThatRan["Stop"] { + return fmt.Errorf("the check ran %+v on %s, want at least one Start and one Stop", w.startStopCalls, id) + } + return nil +} + +// buildManifest gives the manifest the id and the parts, a backend or only a frontend. +func (w *pluginChecksWorld) buildManifest(id, parts string) { + if parts == "a backend" { + w.manifest = wire.Manifest{ID: id, Name: id, Backend: "example.com/app/plugins/" + id} + return + } + w.manifest = wire.Manifest{ID: id, Name: id, Frontend: "@example/plugin-" + id} +} + +// reserveIDs has the application reserve the ids of list. +func (w *pluginChecksWorld) reserveIDs(list string) { + w.reservedIDs = names(list) +} + +// checkID checks the manifest's id against the reserved ids, noting the error. +func (w *pluginChecksWorld) checkID() { + w.idCheckErr = wire.CheckID(w.manifest, w.reservedIDs) +} + +// idCheckPasses checks that the id check answered no error. +func (w *pluginChecksWorld) idCheckPasses() error { + if w.idCheckErr != nil { + return fmt.Errorf("the id check rejects the id with: %v", w.idCheckErr) + } + return nil +} + +// idCheckRejectsWith checks that the id check answered an error reading want. +func (w *pluginChecksWorld) idCheckRejectsWith(want string) error { + if w.idCheckErr == nil || w.idCheckErr.Error() != want { + return fmt.Errorf("the id check answers %v, want the error %q", w.idCheckErr, want) + } + return nil +} + +// endScenario closes the channel each held call of the scenario waits on, returning every one of those calls. +func (w *pluginChecksWorld) endScenario(ctx context.Context, _ *godog.Scenario, _ error) (context.Context, error) { + close(w.endOfScenario) + return ctx, nil +} + +// givenPluginChecks registers the steps that name the fake plugin and the promises it breaks. +func givenPluginChecks(sc *godog.ScenarioContext, w *pluginChecksWorld) { + sc.Step(`^the plugin "([^"]*)" keeps every promise$`, w.keepEveryPromise) + sc.Step(`^the plugin "([^"]*)" has no routes and no public paths$`, w.leaveOutRoutes) + sc.Step(`^the plugin "([^"]*)" answers the error "([^"]*)" from (`+errorCallsPattern+`)$`, w.answerError) + sc.Step(`^the plugin "([^"]*)" panics with "([^"]*)" in (`+callsPattern+`)$`, w.panicIn) + sc.Step(`^the plugin "([^"]*)" never returns from (`+callsPattern+`)$`, w.blockCall) + sc.Step(`^the plugin "([^"]*)" takes (\S+) in Register$`, w.delayRegister) + sc.Step(`^the plugin "([^"]*)" answers no plugin from Register$`, w.answerNoPlugin) + sc.Step(`^the plugin "([^"]*)" answers no handler from Routes$`, w.answerNoHandler) + sc.Step(`^the plugin "([^"]*)" calls itself "([^"]*)"$`, w.claimID) +} + +// givenIDCheck registers the steps that write a manifest and the ids the application reserves. +func givenIDCheck(sc *godog.ScenarioContext, w *pluginChecksWorld) { + sc.Step(`^a manifest with the id "([^"]*)" and (a backend|only a frontend)$`, w.buildManifest) + sc.Step(`^the application reserves the ids ((?:"[^"]*"(?:, | and )?)+)$`, w.reserveIDs) +} + +// whenPluginChecks registers the steps that check the fake plugin's lifecycle or the manifest's id. +func whenPluginChecks(sc *godog.ScenarioContext, w *pluginChecksWorld) { + sc.Step(`^the application checks the lifecycle of "([^"]*)" with a time limit of (\S+)$`, w.checkLifecycle) + sc.Step(`^the application checks the manifest's id$`, w.checkID) +} + +// thenPluginChecks registers the steps that check the findings, the dependencies, the contexts and the id check. +func thenPluginChecks(sc *godog.ScenarioContext, w *pluginChecksWorld) { + sc.Step(`^the check gives no finding$`, w.noFinding) + sc.Step(`^the check gives one finding, under the rule "([^"]*)"$`, w.oneFindingUnder) + sc.Step(`^its (problem|fix) reads: (.+)$`, w.findingReads) + sc.Step(`^the check gives these findings, in this order:$`, w.findingsInOrder) + sc.Step(`^every Register of "([^"]*)" received dependencies built for it alone$`, w.onePluginPerCheck) + sc.Step(`^every Start and Stop of "([^"]*)" got a context that ends within (\S+) of the call$`, + w.contextsEndWithin) + sc.Step(`^the id check passes$`, w.idCheckPasses) + sc.Step(`^the id check rejects it with: (.+)$`, w.idCheckRejectsWith) +} + +// initializePluginChecks gives each scenario of the plugin checks feature a world of its own and its steps. +func initializePluginChecks() func(*godog.ScenarioContext) { + return func(sc *godog.ScenarioContext) { + w := &pluginChecksWorld{ + endOfScenario: make(chan struct{}), hasRoutes: true, faults: map[string]func(){}, + callErrors: map[string]error{}, + } + sc.After(w.endScenario) + givenPluginChecks(sc, w) + givenIDCheck(sc, w) + whenPluginChecks(sc, w) + thenPluginChecks(sc, w) + } +} From d974c78bb5e5c382fd564425b79f7367a77c1e98 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 29 Nov 2026 19:12:58 +0100 Subject: [PATCH 06/11] docs(pluginkit): list the plugin checks under Unreleased --- pluginkit/CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pluginkit/CHANGELOG.md b/pluginkit/CHANGELOG.md index 661f104..66711df 100644 --- a/pluginkit/CHANGELOG.md +++ b/pluginkit/CHANGELOG.md @@ -29,6 +29,8 @@ Releases of this module are tagged `pluginkit/vX.Y.Z`. Releases up to - `Schema.FormFields` describes each field for a settings form as a `FormField`, in manifest order, and a secret only as set or not set. - A duration `Value` keeps the text it was read from in `Text`, so `2h` stays `2h`. - `ScreenGate` is an optional interface whose `ShowsScreens` tells an application whether a plugin's admin menu entries and screens show for the caller in the context. +- `plugintest.LifecycleFindings` checks the promises of the plugin contract from a plugin's own tests, each check on a new plugin within a time limit the application passes, and answers one `Finding` per broken promise with its rule, problem and fix. +- `wire.CheckID` checks one manifest's id against the reserved ids and the generated wiring, as `Load` does. - The module needs Go 1.27.4. ## 0.12.0 - 2026-11-07 From b740e8f80697c214cc78c16353698ff99843b6c4 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 29 Nov 2026 19:42:52 +0100 Subject: [PATCH 07/11] refactor(pluginkit): rename the weak names of the functions the move touches --- pluginkit/boot.go | 6 ++-- pluginkit/hook.go | 54 ++++++++++++++--------------- pluginkit/host.go | 73 +++++++++++++++++++-------------------- pluginkit/protect.go | 19 +++++----- pluginkit/recover.go | 25 +++++++------- pluginkit/registration.go | 10 +++--- pluginkit/routes.go | 2 +- pluginkit/start_each.go | 38 ++++++++++---------- 8 files changed, 114 insertions(+), 113 deletions(-) diff --git a/pluginkit/boot.go b/pluginkit/boot.go index 3f56de9..eb6c537 100644 --- a/pluginkit/boot.go +++ b/pluginkit/boot.go @@ -16,7 +16,7 @@ type Boot struct { // NewBoot reads every record of store once. func NewBoot(ctx context.Context, store PluginStore) (*Boot, error) { var records map[string]PluginRecord - err := guarded(ctx, "read the plugin records", func(ctx context.Context) error { + err := runWithRecover(ctx, "read the plugin records", func(ctx context.Context) error { var readErr error records, readErr = store.Records(ctx) return readErr @@ -79,14 +79,14 @@ func (b *Boot) admit(ctx context.Context, id string) (bool, error) { // Pause pauses the plugin the failure names, recording its step and its reason apart. func (b *Boot) Pause(ctx context.Context, failure Failure) error { - return guarded(ctx, "pause "+failure.ID, func(ctx context.Context) error { + return runWithRecover(ctx, "pause "+failure.ID, func(ctx context.Context) error { return b.store.Pause(ctx, failure.ID, failure.Step, failure.Reason) }) } // activate marks the plugin id active and clears its step and its error. func (b *Boot) activate(ctx context.Context, id string) error { - return guarded(ctx, "activate "+id, func(ctx context.Context) error { return b.store.Activate(ctx, id) }) + return runWithRecover(ctx, "activate "+id, func(ctx context.Context) error { return b.store.Activate(ctx, id) }) } // Started pauses each plugin that failed to migrate or start, and activates each paused plugin that started. diff --git a/pluginkit/hook.go b/pluginkit/hook.go index 4979729..9c840fd 100644 --- a/pluginkit/hook.go +++ b/pluginkit/hook.go @@ -180,24 +180,24 @@ func (h *Hook[C]) Stats() HookStats { // fire runs one firing, counting an overrun, charged to the slowest plugin when timed plugins ran over together. func (h *Hook[C]) fire(ctx context.Context, call func(context.Context, C) error) { h.firings.Add(1) - began := time.Now() - ctx, cancel := context.WithDeadline(ctx, began.Add(h.settings.Budget)) + firingStart := time.Now() + ctx, cancel := context.WithDeadline(ctx, firingStart.Add(h.settings.Budget)) defer cancel() - timed, slowest := h.takeTimedFiring(), -1 - if timed { - slowest = h.callTimed(ctx, call) + isTimed, slowestIndex := h.takeTimedFiring(), -1 + if isTimed { + slowestIndex = h.slowestPluginIndex(ctx, call) } else { for i, plugin := range h.plugins { - h.report(i, run(ctx, plugin, call)) + h.report(i, outcomeOf(ctx, plugin, call)) } } - if time.Since(began) <= h.settings.Budget { + if time.Since(firingStart) <= h.settings.Budget { return } h.overruns.Add(1) - if slowest >= 0 { - h.counters[slowest].overruns.Add(1) - } else if timed { + if slowestIndex >= 0 { + h.counters[slowestIndex].overruns.Add(1) + } else if isTimed { h.uncharged.Add(1) } h.timed.Store(int64(h.settings.TimedFirings)) @@ -216,25 +216,25 @@ func (h *Hook[C]) takeTimedFiring() bool { } } -// callTimed calls and times every plugin in order, returning the slowest, or -1 when together they kept the budget. -func (h *Hook[C]) callTimed(ctx context.Context, call func(context.Context, C) error) int { - slowest, longest, total := 0, time.Duration(0), time.Duration(0) +// slowestPluginIndex calls and times every plugin in order, returning the slowest one's index, or -1 within the budget. +func (h *Hook[C]) slowestPluginIndex(ctx context.Context, call func(context.Context, C) error) int { + slowestIndex, longestDuration, totalDuration := 0, time.Duration(0), time.Duration(0) for i, plugin := range h.plugins { - began := time.Now() - out := run(ctx, plugin, call) - took := time.Since(began) - total += took + callStart := time.Now() + callOutcome := outcomeOf(ctx, plugin, call) + callDuration := time.Since(callStart) + totalDuration += callDuration h.counters[i].timedCalls.Add(1) - h.counters[i].timedTime.Add(int64(took)) - if took > longest { - slowest, longest = i, took + h.counters[i].timedTime.Add(int64(callDuration)) + if callDuration > longestDuration { + slowestIndex, longestDuration = i, callDuration } - h.reportTime.Add(int64(h.report(i, out))) + h.reportTime.Add(int64(h.report(i, callOutcome))) } - if total <= h.settings.Budget { + if totalDuration <= h.settings.Budget { return -1 } - return slowest + return slowestIndex } // report counts and reports what went wrong in one call of plugin i, if anything did, returning the time Report took. @@ -279,11 +279,11 @@ type outcome struct { ended bool } -// run calls one plugin inside a recover, answering nil when the call succeeded, else what went wrong. -func run[C any](ctx context.Context, plugin C, call func(context.Context, C) error) (out *outcome) { +// outcomeOf calls one plugin inside a recover and returns what went wrong, or nil when the call returned nil. +func outcomeOf[C any](ctx context.Context, plugin C, call func(context.Context, C) error) (callOutcome *outcome) { defer func() { - if recovered := recover(); recovered != nil { - out = &outcome{panicked: true, stack: string(debug.Stack()), text: anyvalue.Text(recovered)} + if panicValue := recover(); panicValue != nil { + callOutcome = &outcome{panicked: true, stack: string(debug.Stack()), text: anyvalue.Text(panicValue)} } }() if err := call(ctx, plugin); err != nil { diff --git a/pluginkit/host.go b/pluginkit/host.go index be73d8b..76f7465 100644 --- a/pluginkit/host.go +++ b/pluginkit/host.go @@ -69,7 +69,7 @@ func (h *Host) Start(ctx context.Context, stopGrace time.Duration) error { return err } for i, p := range h.plugins { - if err := safeCall(ctx, p.ID(), "start", p.Start); err != nil { + if err := runPluginOperation(ctx, p.ID(), "start", p.Start); err != nil { return errors.Join(err, h.rollBack(ctx, stopGrace, i-1)) } } @@ -103,7 +103,7 @@ func (h *Host) readVersions(ctx context.Context) (map[string]string, error) { if h.store == nil { return versions, nil } - err := guarded(ctx, "read the migration versions", func(ctx context.Context) error { + err := runWithRecover(ctx, "read the migration versions", func(ctx context.Context) error { var err error versions, err = h.store.Versions(ctx) return err @@ -111,33 +111,33 @@ func (h *Host) readVersions(ctx context.Context) (map[string]string, error) { return versions, err } -// migrateUnlessCurrent applies and records p's schema unless versions holds it, answering the step an error came from. -func (h *Host) migrateUnlessCurrent(ctx context.Context, p Plugin, versions map[string]string) (Step, error) { - migrator, ok, err := h.migratorFor(ctx, p) +// migrateUnlessCurrent applies and records plugin's schema unless versions holds it, answering the step of any error. +func (h *Host) migrateUnlessCurrent(ctx context.Context, plugin Plugin, versions map[string]string) (Step, error) { + migrator, ok, err := h.migratorFor(ctx, plugin) if err != nil || !ok { return StepMigrate, err } versioner, ok := migrator.(MigrationVersioner) if !ok || h.store == nil { - return StepMigrate, safeCall(ctx, p.ID(), "migrate", migrator.Migrate) + return StepMigrate, runPluginOperation(ctx, plugin.ID(), "migrate", migrator.Migrate) } - version, err := migrationVersion(ctx, p.ID(), versioner) - if err != nil || version == versions[p.ID()] { + version, err := migrationVersion(ctx, plugin.ID(), versioner) + if err != nil || version == versions[plugin.ID()] { return StepMigrate, err } - if err := safeCall(ctx, p.ID(), "migrate", migrator.Migrate); err != nil { + if err := runPluginOperation(ctx, plugin.ID(), "migrate", migrator.Migrate); err != nil { return StepMigrate, err } - return StepRecord, safeCall(ctx, p.ID(), "record", func(ctx context.Context) error { - return h.store.Record(ctx, p.ID(), version) + return StepRecord, runPluginOperation(ctx, plugin.ID(), "record", func(ctx context.Context) error { + return h.store.Record(ctx, plugin.ID(), version) }) } -// migratorFor returns the [Migrator] the lookup gives for p, or p itself when the lookup gives none. -func (h *Host) migratorFor(ctx context.Context, p Plugin) (migrator Migrator, ok bool, err error) { +// migratorFor returns the [Migrator] the lookup gives for plugin, or plugin itself when the lookup gives none. +func (h *Host) migratorFor(ctx context.Context, plugin Plugin) (migrator Migrator, ok bool, err error) { if h.migratorOf != nil { - err = safeCall(ctx, p.ID(), "migrator lookup", func(context.Context) error { - migrator, ok = h.migratorOf(p) + err = runPluginOperation(ctx, plugin.ID(), "migrator lookup", func(context.Context) error { + migrator, ok = h.migratorOf(plugin) if ok && migrator == nil { return errNilMigrator } @@ -147,14 +147,14 @@ func (h *Host) migratorFor(ctx context.Context, p Plugin) (migrator Migrator, ok return migrator, ok, err } } - migrator, ok = p.(Migrator) + migrator, ok = plugin.(Migrator) return migrator, ok, nil } // migrationVersion returns the migration version versioner reports for the plugin id, refusing an empty one. func migrationVersion(ctx context.Context, id string, versioner MigrationVersioner) (string, error) { var version string - err := safeCall(ctx, id, "migration version", func(context.Context) error { + err := runPluginOperation(ctx, id, "migration version", func(context.Context) error { var err error if version, err = versioner.MigrationVersion(); err == nil && version == "" { err = errEmptyMigrationVersion @@ -172,7 +172,7 @@ func (h *Host) Seed(ctx context.Context) error { if !ok { continue } - if err := safeCall(ctx, p.ID(), "seed", seeder.Seed); err != nil { + if err := runPluginOperation(ctx, p.ID(), "seed", seeder.Seed); err != nil { return err } } @@ -213,57 +213,56 @@ func (h *Host) Stop(ctx context.Context) error { func (h *Host) stopDownFrom(ctx context.Context, index int) error { var errs []error for i := index; i >= 0; i-- { - if err := safeCall(ctx, h.plugins[i].ID(), "stop", h.plugins[i].Stop); err != nil { + if err := runPluginOperation(ctx, h.plugins[i].ID(), "stop", h.plugins[i].Stop); err != nil { errs = append(errs, err) } } return errors.Join(errs...) } -// safeCall runs fn, wrapping any returned error and converting any panic into an error tagged with the -// plugin id and operation. -func safeCall(ctx context.Context, id, operation string, fn func(context.Context) error) error { - return guarded(ctx, id+" "+operation, fn) +// runPluginOperation runs call through [runWithRecover], naming the plugin id and the operation in any failure. +func runPluginOperation(ctx context.Context, id, operation string, call func(context.Context) error) error { + return runWithRecover(ctx, id+" "+operation, call) } -// guarded runs fn, wrapping any returned error and converting any panic into an error tagged with name. -func guarded(ctx context.Context, name string, fn func(context.Context) error) (err error) { +// runWithRecover runs call inside a recover, wrapping any error it returns and turning any panic into an error. +func runWithRecover(ctx context.Context, name string, call func(context.Context) error) (err error) { defer func() { - if recovered := recover(); recovered != nil { - err = guardedPanic{name: name, value: anyvalue.Text(recovered)} + if panicValue := recover(); panicValue != nil { + err = callPanic{name: name, value: anyvalue.Text(panicValue)} } }() - if err := fn(ctx); err != nil { - return &guardedError{name: name, text: fmt.Sprint(err), err: err} + if err := call(ctx); err != nil { + return &callError{name: name, text: fmt.Sprint(err), err: err} } return nil } -// guardedError is an error [guarded] wrapped, keeping its text, read once inside the recover, apart from the name. -type guardedError struct { +// callError is an error [runWithRecover] wrapped, its text read once inside the recover, kept apart from the name. +type callError struct { name string text string err error } // Error returns the text of the error with the name in front, as a log line prints it. -func (e *guardedError) Error() string { +func (e *callError) Error() string { return "pluginkit: " + e.name + ": " + e.text } -// Unwrap returns the error fn returned. -func (e *guardedError) Unwrap() error { +// Unwrap returns the error the call returned. +func (e *callError) Unwrap() error { return e.err } -// guardedPanic is a panic [guarded] recovered, keeping the name it puts in front apart from the panic's value. -type guardedPanic struct { +// callPanic is a panic [runWithRecover] recovered, keeping the name it puts in front apart from the panic's value. +type callPanic struct { name string value string } // Error returns the text of the panic with the name in front, as a log line prints it. -func (e guardedPanic) Error() string { +func (e callPanic) Error() string { return "pluginkit: " + e.name + " panicked: " + e.value } diff --git a/pluginkit/protect.go b/pluginkit/protect.go index c8e6ddf..0a53d65 100644 --- a/pluginkit/protect.go +++ b/pluginkit/protect.go @@ -22,22 +22,23 @@ type RouteSettings struct { // Protect serves the handler of plugin id behind settings.Wrap and its public paths without it, recovering each panic. func Protect(id string, handler http.Handler, publicPaths []string, settings RouteSettings) http.Handler { checkRouteSettings(id, settings) - public := make(map[string]struct{}, len(publicPaths)) + publicPathSet := make(map[string]struct{}, len(publicPaths)) for _, path := range publicPaths { - public[path] = struct{}{} + publicPathSet[path] = struct{}{} } - plugin := &recovered{id: id, handler: handler, settings: settings} - protected := settings.Wrap(plugin) - if anyvalue.IsNil(protected) { + recoveryHandler := &panicRecoveryHandler{id: id, handler: handler, settings: settings} + middlewareHandler := settings.Wrap(recoveryHandler) + if anyvalue.IsNil(middlewareHandler) { panic("pluginkit: Protect: RouteSettings.Wrap answered no handler") } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if _, ok := public[r.URL.Path]; ok { - plugin.ServeHTTP(w, r) + if _, ok := publicPathSet[r.URL.Path]; ok { + recoveryHandler.ServeHTTP(w, r) return } - outer := &routeWriter{ResponseWriter: w, http1: r.ProtoMajor == 1} - protected.ServeHTTP(outer, r.WithContext(context.WithValue(r.Context(), middlewareWriter{}, outer))) + outerWriter := &routeWriter{ResponseWriter: w, http1: r.ProtoMajor == 1} + writerContext := context.WithValue(r.Context(), middlewareWriter{}, outerWriter) + middlewareHandler.ServeHTTP(outerWriter, r.WithContext(writerContext)) }) } diff --git a/pluginkit/recover.go b/pluginkit/recover.go index 828dde0..3b06164 100644 --- a/pluginkit/recover.go +++ b/pluginkit/recover.go @@ -27,8 +27,8 @@ type RouteFailure struct { Stack string } -// recovered serves one plugin's handler, reporting each panic of it and answering it while nothing went out. -type recovered struct { +// panicRecoveryHandler serves one plugin's handler, reporting each panic of it and answering it while nothing went out. +type panicRecoveryHandler struct { id string handler http.Handler settings RouteSettings @@ -38,7 +38,7 @@ type recovered struct { type middlewareWriter struct{} // ServeHTTP serves the plugin's handler through a writer that notes whether the plugin's answer began. -func (h *recovered) ServeHTTP(w http.ResponseWriter, r *http.Request) { +func (h *panicRecoveryHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { writer := &routeWriter{ResponseWriter: w, http1: r.ProtoMajor == 1} defer h.finish(writer, w.Header().Clone(), r) h.handler.ServeHTTP(writer, r) @@ -51,23 +51,24 @@ func begunBefore(r *http.Request) bool { } // finish recovers a panic of the plugin's handler, reports it, then answers it or cuts the answer the plugin began. -func (h *recovered) finish(writer *routeWriter, header http.Header, r *http.Request) { - caught := recover() - if caught == nil { +func (h *panicRecoveryHandler) finish(writer *routeWriter, header http.Header, r *http.Request) { + panicValue := recover() + if panicValue == nil { return } if writer.hijacked != nil { _ = writer.hijacked.Close() } - if caught == http.ErrAbortHandler { - panic(caught) + if panicValue == http.ErrAbortHandler { + panic(panicValue) } - begun := writer.begun.Load() || begunBefore(r) + hasAnswerBegun := writer.begun.Load() || begunBefore(r) h.settings.Report(RouteFailure{ - ID: h.id, Method: r.Method, Path: r.URL.Path, Answered: !begun, - Err: panicError("pluginkit: " + h.id + " route panicked: " + anyvalue.Text(caught)), Stack: string(debug.Stack()), + ID: h.id, Method: r.Method, Path: r.URL.Path, Answered: !hasAnswerBegun, + Err: panicError("pluginkit: " + h.id + " route panicked: " + anyvalue.Text(panicValue)), + Stack: string(debug.Stack()), }) - if begun { + if hasAnswerBegun { panic(http.ErrAbortHandler) } clear(writer.Header()) diff --git a/pluginkit/registration.go b/pluginkit/registration.go index 64362bd..1b340b3 100644 --- a/pluginkit/registration.go +++ b/pluginkit/registration.go @@ -41,18 +41,18 @@ func RegisterEach[D any, P interface{ ID() string }]( return outcome } -// register calls entry's Register with deps inside a recover, naming the plugin in any failure. -func register[D any, P interface{ ID() string }](entry Registration[D, P], deps D) (plugin P, err error) { - err = guarded(context.Background(), entry.ID+" "+string(StepRegister), func(context.Context) error { +// register calls registration's Register with deps inside a recover, naming the plugin in any failure. +func register[D any, P interface{ ID() string }](registration Registration[D, P], deps D) (plugin P, err error) { + err = runWithRecover(context.Background(), registration.ID+" "+string(StepRegister), func(context.Context) error { var registerErr error - plugin, registerErr = entry.Register(deps) + plugin, registerErr = registration.Register(deps) if registerErr != nil { return registerErr } if anyvalue.IsNil(plugin) { return errNoPlugin } - if id := plugin.ID(); id != entry.ID { + if id := plugin.ID(); id != registration.ID { return fmt.Errorf("the plugin calls itself %q", id) } return nil diff --git a/pluginkit/routes.go b/pluginkit/routes.go index 3e5061a..cf2d1a1 100644 --- a/pluginkit/routes.go +++ b/pluginkit/routes.go @@ -25,7 +25,7 @@ func RoutesEach[P interface{ ID() string }](plugins []P) RoutesOutcome { outcome := RoutesOutcome{Routes: map[string]http.Handler{}, PublicPaths: map[string][]string{}} for _, plugin := range plugins { id := plugin.ID() - err := guarded(context.Background(), id+" "+string(StepRoutes), func(context.Context) error { + err := runWithRecover(context.Background(), id+" "+string(StepRoutes), func(context.Context) error { return outcome.read(id, plugin) }) if err != nil { diff --git a/pluginkit/start_each.go b/pluginkit/start_each.go index ec3c499..660bad7 100644 --- a/pluginkit/start_each.go +++ b/pluginkit/start_each.go @@ -66,43 +66,43 @@ func (h *Host) StartEach(ctx context.Context) (StartOutcome, error) { return outcome, nil } -// migrateUnlessEnded migrates p while ctx lasts, answering a [Failure] whose Err is nil when nothing failed. -func (h *Host) migrateUnlessEnded(ctx context.Context, p Plugin, versions map[string]string) Failure { - if err := safeCall(ctx, p.ID(), string(StepMigrate), context.Context.Err); err != nil { - return failureOf(p.ID(), StepMigrate, err) +// migrateUnlessEnded migrates plugin while ctx lasts, answering a [Failure] whose Err is nil when nothing failed. +func (h *Host) migrateUnlessEnded(ctx context.Context, plugin Plugin, versions map[string]string) Failure { + if err := runPluginOperation(ctx, plugin.ID(), string(StepMigrate), context.Context.Err); err != nil { + return failureOf(plugin.ID(), StepMigrate, err) } - step, err := h.migrateUnlessCurrent(ctx, p, versions) - return failureOf(p.ID(), step, err) + step, err := h.migrateUnlessCurrent(ctx, plugin, versions) + return failureOf(plugin.ID(), step, err) } -// startAfter lists what p's migration did when it failed, then starts p unless that failure rules it out. -func (o *StartOutcome) startAfter(ctx context.Context, p Plugin, migration Failure) { +// startAfter lists what plugin's migration did when it failed, then starts plugin unless that failure rules it out. +func (o *StartOutcome) startAfter(ctx context.Context, plugin Plugin, migration Failure) { if migration.Err != nil { o.Failed = append(o.Failed, migration) } if migration.Err != nil && migration.Step != StepRecord { return } - began := time.Now() - err := safeCall(ctx, p.ID(), string(StepStart), context.Context.Err) + startTime := time.Now() + err := runPluginOperation(ctx, plugin.ID(), string(StepStart), context.Context.Err) if err == nil { - err = safeCall(ctx, p.ID(), string(StepStart), p.Start) + err = runPluginOperation(ctx, plugin.ID(), string(StepStart), plugin.Start) } if err != nil { - o.Failed = append(o.Failed, failureOf(p.ID(), StepStart, err)) + o.Failed = append(o.Failed, failureOf(plugin.ID(), StepStart, err)) return } - o.Started = append(o.Started, StartedPlugin{ID: p.ID(), Took: time.Since(began)}) + o.Started = append(o.Started, StartedPlugin{ID: plugin.ID(), Took: time.Since(startTime)}) } -// failureOf returns the failure of the plugin id at step, its reason the text [guarded] read, calling no plugin code. +// failureOf returns the failure of the plugin id at step, its reason read by [runWithRecover], calling no plugin code. func failureOf(id string, step Step, err error) Failure { failure := Failure{ID: id, Step: step, Err: err} - switch guardedErr := err.(type) { - case guardedPanic: - failure.Panicked, failure.Reason = true, "panicked: "+guardedErr.value - case *guardedError: - failure.Reason = guardedErr.text + switch runError := err.(type) { + case callPanic: + failure.Panicked, failure.Reason = true, "panicked: "+runError.value + case *callError: + failure.Reason = runError.text } return failure } From e37548db6dd09d32260a6110ce0a3f49833930b9 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 29 Nov 2026 22:53:18 +0100 Subject: [PATCH 08/11] fix(pluginkit): judge a call at the time limit by whether it returned before it --- pluginkit/plugintest/call.go | 25 ++++++++++- pluginkit/plugintest/call_test.go | 73 +++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+), 2 deletions(-) diff --git a/pluginkit/plugintest/call.go b/pluginkit/plugintest/call.go index 73b3928..cda940b 100644 --- a/pluginkit/plugintest/call.go +++ b/pluginkit/plugintest/call.go @@ -23,15 +23,36 @@ type callOutcome[T any] struct { func outcomeOf[T any](name string, stepBudget time.Duration, call func(context.Context) (T, error)) callOutcome[T] { ctx, cancel := context.WithTimeout(context.Background(), stepBudget) defer cancel() + overBudgetOutcome := callOutcome[T]{ + problem: name + " did not return within " + stepBudget.String(), isOverBudget: true, + } outcomes := make(chan callOutcome[T], 1) go func() { - outcomes <- outcomeWithRecover(ctx, name, call) + outcomes <- outcomeAtReturn(ctx, outcomeWithRecover(ctx, name, call), overBudgetOutcome) }() select { case outcome := <-outcomes: return outcome case <-ctx.Done(): - return callOutcome[T]{problem: name + " did not return within " + stepBudget.String(), isOverBudget: true} + return outcomeAtDeadline(outcomes, overBudgetOutcome) + } +} + +// outcomeAtReturn returns outcome, or overBudgetOutcome when ctx ended before the call that gave outcome returned. +func outcomeAtReturn[T any](ctx context.Context, outcome, overBudgetOutcome callOutcome[T]) callOutcome[T] { + if ctx.Err() != nil { + return overBudgetOutcome + } + return outcome +} + +// outcomeAtDeadline returns the outcome the call already sent on outcomes, or overBudgetOutcome when it sent none. +func outcomeAtDeadline[T any](outcomes <-chan callOutcome[T], overBudgetOutcome callOutcome[T]) callOutcome[T] { + select { + case outcome := <-outcomes: + return outcome + default: + return overBudgetOutcome } } diff --git a/pluginkit/plugintest/call_test.go b/pluginkit/plugintest/call_test.go index f426071..07ce4af 100644 --- a/pluginkit/plugintest/call_test.go +++ b/pluginkit/plugintest/call_test.go @@ -91,6 +91,79 @@ func TestOutcomeOfNamesTheErrorOrThePanicThatEndedACall(t *testing.T) { } } +func TestOutcomeOfCutsACallThatReturnsOnlyOnceItsContextEnds(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + outcome := outcomeOf("the first Start", testBudget, func(ctx context.Context) (int, error) { + <-ctx.Done() + return 42, nil + }) + + if outcome != firstStartOverBudgetOutcome { + t.Errorf("outcome = %+v, want %+v", outcome, firstStartOverBudgetOutcome) + } + }) +} + +// firstStartOverBudgetOutcome is the outcome of a first Start that did not return within testBudget. +var firstStartOverBudgetOutcome = callOutcome[int]{ + problem: "the first Start did not return within 50ms", isOverBudget: true, +} + +func TestOutcomeAtReturnAnswersTheOutcomeOfACallBeforeItsContextEndedElseOverBudget(t *testing.T) { + t.Parallel() + + tests := map[string]struct { + hasContextEnded bool + want callOutcome[int] + }{ + "a call that returned before its context ended": {false, callOutcome[int]{answer: 42}}, + "a call that returned after its context ended": {true, firstStartOverBudgetOutcome}, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + if tc.hasContextEnded { + cancel() + } + + if outcome := outcomeAtReturn(ctx, callOutcome[int]{answer: 42}, firstStartOverBudgetOutcome); outcome != tc.want { + t.Errorf("outcome = %+v, want %+v", outcome, tc.want) + } + }) + } +} + +func TestOutcomeAtDeadlineAnswersTheOutcomeACallSentElseOverBudget(t *testing.T) { + t.Parallel() + + tests := map[string]struct { + sentOutcomes []callOutcome[int] + want callOutcome[int] + }{ + "a call that sent its outcome": {[]callOutcome[int]{{answer: 42}}, callOutcome[int]{answer: 42}}, + "a call that sent nothing": {nil, firstStartOverBudgetOutcome}, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + outcomes := make(chan callOutcome[int], 1) + for _, sentOutcome := range tc.sentOutcomes { + outcomes <- sentOutcome + } + + if outcome := outcomeAtDeadline(outcomes, firstStartOverBudgetOutcome); outcome != tc.want { + t.Errorf("outcome = %+v, want %+v", outcome, tc.want) + } + }) + } +} + func TestOutcomeOfCutsACallThatDoesNotReturnWithinTheStepBudget(t *testing.T) { t.Parallel() From 5d5461febb3f28d6c12b43ac04f91b0479bd4c58 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 29 Nov 2026 22:53:19 +0100 Subject: [PATCH 09/11] fix(pluginkit): check PublicPaths on a plugin of its own, apart from Routes --- pluginkit/features/plugin-checks.feature | 8 +++ .../features/steps_plugin_checks_test.go | 32 ++++++++++-- pluginkit/plugintest/lifecycle.go | 23 ++++++--- pluginkit/plugintest/lifecycle_test.go | 50 +++++++++++++++++-- 4 files changed, 97 insertions(+), 16 deletions(-) diff --git a/pluginkit/features/plugin-checks.feature b/pluginkit/features/plugin-checks.feature index 0bf76ef..1579d18 100644 --- a/pluginkit/features/plugin-checks.feature +++ b/pluginkit/features/plugin-checks.feature @@ -80,6 +80,14 @@ Feature: Checking the promises a plugin makes to its host from its own tests | routes-before-start | Routes before Start did not return within 200ms | | start-stop-again | the second Start answered the error: already started | + Scenario: A Routes that never returns does not hold up the check of PublicPaths + Given the plugin "events" guards Routes and PublicPaths with one lock + And the plugin "events" never returns from Routes + When the application checks the lifecycle of "events" with a time limit of 200ms + Then the check gives these findings, in this order: + | rule | problem | + | routes-before-start | Routes before Start did not return within 200ms | + Scenario: Start and Stop each get a context that ends at the time limit Given the plugin "events" keeps every promise When the application checks the lifecycle of "events" with a time limit of 200ms diff --git a/pluginkit/features/steps_plugin_checks_test.go b/pluginkit/features/steps_plugin_checks_test.go index e6bdb4a..d086c6f 100644 --- a/pluginkit/features/steps_plugin_checks_test.go +++ b/pluginkit/features/steps_plugin_checks_test.go @@ -35,7 +35,7 @@ var stopCallNames = []string{ } // firstCallOfEachCheck names the first call each check makes of the plugin it registers, none for the register check. -var firstCallOfEachCheck = []string{"", "Routes", "Stop before any Start", "the first Start"} +var firstCallOfEachCheck = []string{"", "Routes", "PublicPaths", "Stop before any Start", "the first Start"} // fakeDeps is what a plugin checks scenario lends each Register: the count of dependencies built, this one included. type fakeDeps struct{ buildNumber int } @@ -55,6 +55,7 @@ type pluginChecksWorld struct { pluginID string claimedID string hasRoutes bool + hasRoutesLock bool answersNoPlugin bool answersNoHandler bool faults map[string]func() @@ -75,6 +76,8 @@ type fakePlugin struct { id string startCount int firstCall string + // routesLock is the lock Routes and PublicPaths take, and nil when the scenario gives the plugin none. + routesLock chan struct{} } // ID returns the id the plugin calls itself. @@ -124,20 +127,33 @@ func (p *fakePlugin) stopCallName() string { // fakePluginWithRoutes is a fake plugin with routes and public paths. type fakePluginWithRoutes struct{ *fakePlugin } -// Routes runs the scenario's fault for Routes, then answers a handler, or none when the scenario says so. +// Routes runs the scenario's fault for Routes under the routes lock, then answers a handler, or none when told to. func (p fakePluginWithRoutes) Routes() http.Handler { + releaseLock := p.takeRoutesLock() + defer releaseLock() p.noteFirstCall("Routes") p.world.runFault("Routes") return p.world.routesHandler() } -// PublicPaths runs the scenario's fault for PublicPaths, then answers one public path. +// PublicPaths runs the scenario's fault for PublicPaths under the routes lock, then answers one public path. func (p fakePluginWithRoutes) PublicPaths() []string { + releaseLock := p.takeRoutesLock() + defer releaseLock() p.noteFirstCall("PublicPaths") p.world.runFault("PublicPaths") return []string{"/health"} } +// takeRoutesLock waits for the routes lock and takes it, when the plugin has one, and returns the release of it. +func (p *fakePlugin) takeRoutesLock() (releaseLock func()) { + if p.routesLock == nil { + return func() {} + } + p.routesLock <- struct{}{} + return func() { <-p.routesLock } +} + // recordCall notes that the Start or Stop method ran now with ctx, and when ctx ends. func (w *pluginChecksWorld) recordCall(ctx context.Context, method string) { deadline, hasDeadline := ctx.Deadline() @@ -194,6 +210,9 @@ func (w *pluginChecksWorld) newPlugin() pluginkit.Plugin { return nil } plugin := &fakePlugin{world: w, id: cmp.Or(w.claimedID, w.pluginID)} + if w.hasRoutesLock { + plugin.routesLock = make(chan struct{}, 1) + } w.plugins = append(w.plugins, plugin) if !w.hasRoutes { return plugin @@ -221,6 +240,12 @@ func (w *pluginChecksWorld) leaveOutRoutes(id string) { w.hasRoutes = false } +// addRoutesLock names the fake plugin id and has its Routes and PublicPaths each take one lock the plugin holds. +func (w *pluginChecksWorld) addRoutesLock(id string) { + w.pluginID = id + w.hasRoutesLock = true +} + // answerError names the fake plugin id and has the call these words name answer an error with text. func (w *pluginChecksWorld) answerError(id, text, call string) { w.pluginID = id @@ -423,6 +448,7 @@ func (w *pluginChecksWorld) endScenario(ctx context.Context, _ *godog.Scenario, func givenPluginChecks(sc *godog.ScenarioContext, w *pluginChecksWorld) { sc.Step(`^the plugin "([^"]*)" keeps every promise$`, w.keepEveryPromise) sc.Step(`^the plugin "([^"]*)" has no routes and no public paths$`, w.leaveOutRoutes) + sc.Step(`^the plugin "([^"]*)" guards Routes and PublicPaths with one lock$`, w.addRoutesLock) sc.Step(`^the plugin "([^"]*)" answers the error "([^"]*)" from (`+errorCallsPattern+`)$`, w.answerError) sc.Step(`^the plugin "([^"]*)" panics with "([^"]*)" in (`+callsPattern+`)$`, w.panicIn) sc.Step(`^the plugin "([^"]*)" never returns from (`+callsPattern+`)$`, w.blockCall) diff --git a/pluginkit/plugintest/lifecycle.go b/pluginkit/plugintest/lifecycle.go index 3559eb9..e6a2974 100644 --- a/pluginkit/plugintest/lifecycle.go +++ b/pluginkit/plugintest/lifecycle.go @@ -31,7 +31,8 @@ const ( // checks are the checks of the plugin contract in order, each run on a new plugin whose Register kept its promises. var checks = []func(plugin pluginkit.Plugin, stepBudget time.Duration) []Finding{ - noFindingsPastRegister, routesBeforeStartFindings, stopWithoutStartFindings, startStopAgainFindings, + noFindingsPastRegister, routesBeforeStartFindings, publicPathsBeforeStartFindings, stopWithoutStartFindings, + startStopAgainFindings, } // LifecycleFindings registers a new plugin from newDeps for each check and returns each promise the plugin breaks. @@ -104,16 +105,22 @@ func noFindingsPastRegister(pluginkit.Plugin, time.Duration) []Finding { return nil } -// routesBeforeStartFindings returns a finding for each of Routes and PublicPaths that breaks its promise before Start. +// routesBeforeStartFindings returns the finding of a Routes that breaks its promise before Start. func routesBeforeStartFindings(plugin pluginkit.Plugin, stepBudget time.Duration) []Finding { - var routesProblem, publicPathsProblem string - if provider, ok := plugin.(pluginkit.RouteProvider); ok { - routesProblem = routesBeforeStartProblem(provider, stepBudget) + provider, ok := plugin.(pluginkit.RouteProvider) + if !ok { + return nil } - if provider, ok := plugin.(pluginkit.PublicPathProvider); ok { - publicPathsProblem = publicPathsBeforeStartProblem(provider, stepBudget) + return findingsOf(RuleRoutesBeforeStart, fixRoutesBeforeStart, routesBeforeStartProblem(provider, stepBudget)) +} + +// publicPathsBeforeStartFindings returns the finding of a PublicPaths that breaks its promise before Start. +func publicPathsBeforeStartFindings(plugin pluginkit.Plugin, stepBudget time.Duration) []Finding { + provider, ok := plugin.(pluginkit.PublicPathProvider) + if !ok { + return nil } - return findingsOf(RuleRoutesBeforeStart, fixRoutesBeforeStart, routesProblem, publicPathsProblem) + return findingsOf(RuleRoutesBeforeStart, fixRoutesBeforeStart, publicPathsBeforeStartProblem(provider, stepBudget)) } // routesBeforeStartProblem calls Routes before any Start and returns the promise it broke, or "". diff --git a/pluginkit/plugintest/lifecycle_test.go b/pluginkit/plugintest/lifecycle_test.go index 21724e2..f8542c4 100644 --- a/pluginkit/plugintest/lifecycle_test.go +++ b/pluginkit/plugintest/lifecycle_test.go @@ -279,6 +279,28 @@ func (p handlerPlugin) Routes() http.Handler { return p.handler } +// routesLockPlugin is a plugin held by value whose Routes holds the lock PublicPaths takes until the release. +type routesLockPlugin struct { + valuePlugin + routesLock chan struct{} + release <-chan struct{} +} + +// Routes takes the routes lock and holds it until the release, then answers a handler. +func (p routesLockPlugin) Routes() http.Handler { + p.routesLock <- struct{}{} + <-p.release + <-p.routesLock + return http.NotFoundHandler() +} + +// PublicPaths waits for the routes lock, then answers one path. +func (p routesLockPlugin) PublicPaths() []string { + p.routesLock <- struct{}{} + <-p.routesLock + return []string{"/feed.xml"} +} + // mapHandler is a handler whose type is a map. type mapHandler map[string]string @@ -364,10 +386,11 @@ func wantCalls(t *testing.T, factory *fakePluginFactory, want []string) { // everyCall is each call the checks make of plugins that keep every promise, in order. var everyCall = []string{ "newDeps 1", "Register of deps 1", - "newDeps 2", "Register of deps 2", "Routes before Start of plugin 2", "PublicPaths before Start of plugin 2", - "newDeps 3", "Register of deps 3", "Stop before any Start of plugin 3", - "newDeps 4", "Register of deps 4", "the first Start of plugin 4", "the first Stop of plugin 4", - "the second Start of plugin 4", "the second Stop of plugin 4", + "newDeps 2", "Register of deps 2", "Routes before Start of plugin 2", + "newDeps 3", "Register of deps 3", "PublicPaths before Start of plugin 3", + "newDeps 4", "Register of deps 4", "Stop before any Start of plugin 4", + "newDeps 5", "Register of deps 5", "the first Start of plugin 5", "the first Stop of plugin 5", + "the second Start of plugin 5", "the second Stop of plugin 5", } func TestLifecycleFindingsAnswersNilForAPluginThatKeepsEveryPromise(t *testing.T) { @@ -667,6 +690,23 @@ func TestLifecycleFindingsCutsACallThatNeverReturnsAtTheStepBudgetAndRunsTheLate }) } +func TestLifecycleFindingsChecksPublicPathsOnAPluginOfItsOwnWhileARoutesThatNeverReturnsHoldsItsLock(t *testing.T) { + t.Parallel() + + runWithFakePluginFactory(t, func(t *testing.T, factory *fakePluginFactory) { + registration := pluginkit.Registration[fakeDeps, routesLockPlugin]{ + ID: "events", + Register: func(fakeDeps) (routesLockPlugin, error) { + return routesLockPlugin{routesLock: make(chan struct{}, 1), release: factory.release}, nil + }, + } + + findings := plugintest.LifecycleFindings(registration, factory.newDeps, stepBudget) + + wantFindings(t, findings, []plugintest.Finding{routesFinding("Routes before Start did not return within 50ms")}) + }) +} + func TestLifecycleFindingsNeverBlocksACallThatReturnsAfterItsCheckEnded(t *testing.T) { t.Parallel() @@ -750,7 +790,7 @@ func TestLifecycleFindingsEndsAtARegisterThatBreaksAPromiseForALaterCheck(t *tes routesFinding("Routes before Start answered no handler"), registerFailureFinding("Register answered the error: no database"), }) - wantCalls(t, factory, everyCall[:7]) + wantCalls(t, factory, everyCall[:6]) }) } From 1e24429333062bea992b285a6cab728d7c0318bc Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 29 Nov 2026 23:46:15 +0100 Subject: [PATCH 10/11] feat(pluginkit): check that a second Stop after one Start returns nil --- pluginkit/features/plugin-checks.feature | 46 +++++++------ .../features/steps_plugin_checks_test.go | 32 +++++---- pluginkit/plugintest/lifecycle.go | 26 ++++++- pluginkit/plugintest/lifecycle_test.go | 68 +++++++++++++++---- pluginkit/plugintest/plugintest.go | 2 + 5 files changed, 124 insertions(+), 50 deletions(-) diff --git a/pluginkit/features/plugin-checks.feature b/pluginkit/features/plugin-checks.feature index 1579d18..11645d0 100644 --- a/pluginkit/features/plugin-checks.feature +++ b/pluginkit/features/plugin-checks.feature @@ -4,12 +4,13 @@ Feature: Checking the promises a plugin makes to its host from its own tests holds a plugin to the promises of the plugin contract: Register answers a plugin with its manifest's id within the time limit, Routes and PublicPaths answer before Start runs, Stop works on a plugin that never - started, and Start runs again after Stop. Each check registers a new - plugin from new dependencies, so one broken promise does not hide - another, and a call that never returns is cut at the time limit. Each - finding names its rule, the problem and the fix. An application can - also check one manifest's id against the ids it reserves and the names - the generated wiring uses. + started, Start runs again after Stop, and Stop runs again after Stop. + Each check registers a new plugin from new dependencies, so one broken + promise does not hide another, and a call that never returns is cut at + the time limit. A Start or a Stop that fails before a second Stop is + named once, under start-stop-again. Each finding names its rule, the + problem and the fix. An application can also check one manifest's id + against the ids it reserves and the names the generated wiring uses. Scenario: A plugin that keeps every promise gives no finding Given the plugin "events" keeps every promise @@ -44,31 +45,36 @@ Feature: Checking the promises a plugin makes to its host from its own tests And its fix reads: Examples: - | fault | rule | problem | fix | - | answers no handler from Routes | routes-before-start | Routes before Start answered no handler | Build the handler and the paths in Register, so Routes and PublicPaths answer whether or not Start ran. | - | panics with "boom" in Routes | routes-before-start | Routes before Start panicked: boom | Build the handler and the paths in Register, so Routes and PublicPaths answer whether or not Start ran. | - | never returns from Routes | routes-before-start | Routes before Start did not return within 200ms | Build the handler and the paths in Register, so Routes and PublicPaths answer whether or not Start ran. | - | panics with "boom" in PublicPaths | routes-before-start | PublicPaths before Start panicked: boom | Build the handler and the paths in Register, so Routes and PublicPaths answer whether or not Start ran. | - | answers the error "nothing to close" from Stop before any Start | stop-without-start | Stop before any Start answered the error: nothing to close | Let Stop release only what Start opened, and return nil when Start never ran. | - | panics with "boom" in Stop before any Start | stop-without-start | Stop before any Start panicked: boom | Let Stop release only what Start opened, and return nil when Start never ran. | - | never returns from Stop before any Start | stop-without-start | Stop before any Start did not return within 200ms | Let Stop release only what Start opened, and return nil when Start never ran. | - | answers the error "no route table" from the first Start | start-stop-again | the first Start answered the error: no route table | Let Start open again what Stop released, and let each call return by the time its context ends. | - | never returns from the first Start | start-stop-again | the first Start did not return within 200ms | Let Start open again what Stop released, and let each call return by the time its context ends. | - | answers the error "already closed" from the Stop after the first Start | start-stop-again | the first Stop answered the error: already closed | Let Start open again what Stop released, and let each call return by the time its context ends. | - | answers the error "already started" from the second Start | start-stop-again | the second Start answered the error: already started | Let Start open again what Stop released, and let each call return by the time its context ends. | - | panics with "boom" in the second Start | start-stop-again | the second Start panicked: boom | Let Start open again what Stop released, and let each call return by the time its context ends. | - | panics with "boom" in the Stop after the second Start | start-stop-again | the second Stop panicked: boom | Let Start open again what Stop released, and let each call return by the time its context ends. | + | fault | rule | problem | fix | + | answers no handler from Routes | routes-before-start | Routes before Start answered no handler | Build the handler and the paths in Register, so Routes and PublicPaths answer whether or not Start ran. | + | panics with "boom" in Routes | routes-before-start | Routes before Start panicked: boom | Build the handler and the paths in Register, so Routes and PublicPaths answer whether or not Start ran. | + | never returns from Routes | routes-before-start | Routes before Start did not return within 200ms | Build the handler and the paths in Register, so Routes and PublicPaths answer whether or not Start ran. | + | panics with "boom" in PublicPaths | routes-before-start | PublicPaths before Start panicked: boom | Build the handler and the paths in Register, so Routes and PublicPaths answer whether or not Start ran. | + | answers the error "nothing to close" from Stop before any Start | stop-without-start | Stop before any Start answered the error: nothing to close | Let Stop release only what Start opened, and return nil when Start never ran. | + | panics with "boom" in Stop before any Start | stop-without-start | Stop before any Start panicked: boom | Let Stop release only what Start opened, and return nil when Start never ran. | + | never returns from Stop before any Start | stop-without-start | Stop before any Start did not return within 200ms | Let Stop release only what Start opened, and return nil when Start never ran. | + | answers the error "no route table" from the first Start | start-stop-again | the first Start answered the error: no route table | Let Start open again what Stop released, and let each call return by the time its context ends. | + | never returns from the first Start | start-stop-again | the first Start did not return within 200ms | Let Start open again what Stop released, and let each call return by the time its context ends. | + | answers the error "already closed" from the Stop after the first Start | start-stop-again | the first Stop answered the error: already closed | Let Start open again what Stop released, and let each call return by the time its context ends. | + | answers the error "already started" from the second Start | start-stop-again | the second Start answered the error: already started | Let Start open again what Stop released, and let each call return by the time its context ends. | + | panics with "boom" in the second Start | start-stop-again | the second Start panicked: boom | Let Start open again what Stop released, and let each call return by the time its context ends. | + | panics with "boom" in the Stop after the second Start | start-stop-again | the second Stop panicked: boom | Let Start open again what Stop released, and let each call return by the time its context ends. | + | answers the error "already closed" from the second Stop after the first Start | stop-twice | the second of two Stops answered the error: already closed | Let a second Stop find nothing left to release and return nil. | + | panics with "boom" in the second Stop after the first Start | stop-twice | the second of two Stops panicked: boom | Let a second Stop find nothing left to release and return nil. | + | never returns from the second Stop after the first Start | stop-twice | the second of two Stops did not return within 200ms | Let a second Stop find nothing left to release and return nil. | Scenario: Each check registers a new plugin, so one broken promise does not hide another Given the plugin "events" answers no handler from Routes And the plugin "events" answers the error "nothing to close" from Stop before any Start And the plugin "events" answers the error "already started" from the second Start + And the plugin "events" answers the error "already closed" from the second Stop after the first Start When the application checks the lifecycle of "events" with a time limit of 200ms Then the check gives these findings, in this order: | rule | problem | | routes-before-start | Routes before Start answered no handler | | stop-without-start | Stop before any Start answered the error: nothing to close | | start-stop-again | the second Start answered the error: already started | + | stop-twice | the second of two Stops answered the error: already closed | And every Register of "events" received dependencies built for it alone Scenario: A call that never returns is cut at the time limit and the later checks still run diff --git a/pluginkit/features/steps_plugin_checks_test.go b/pluginkit/features/steps_plugin_checks_test.go index d086c6f..548f63c 100644 --- a/pluginkit/features/steps_plugin_checks_test.go +++ b/pluginkit/features/steps_plugin_checks_test.go @@ -21,7 +21,7 @@ import ( // errorCallsPattern matches the words a step names each call of the fake plugin by that can answer an error. const errorCallsPattern = `Register|Stop before any Start|the first Start|the Stop after the first Start|` + - `the second Start|the Stop after the second Start` + `the second Start|the Stop after the second Start|the second Stop after the first Start` // callsPattern matches the words a step names each call of the fake plugin by. const callsPattern = `Routes|PublicPaths|` + errorCallsPattern @@ -29,13 +29,17 @@ const callsPattern = `Routes|PublicPaths|` + errorCallsPattern // startCallNames names each Start of a fake plugin by the count of Starts before it. var startCallNames = []string{"the first Start", "the second Start"} -// stopCallNames names each Stop of a fake plugin by the count of Starts before it. -var stopCallNames = []string{ - "Stop before any Start", "the Stop after the first Start", "the Stop after the second Start", +// stopCallNames names each Stop of a fake plugin by the count of Starts before it, then the count of Stops since. +var stopCallNames = [][]string{ + {"Stop before any Start"}, + {"the Stop after the first Start", "the second Stop after the first Start"}, + {"the Stop after the second Start"}, } // firstCallOfEachCheck names the first call each check makes of the plugin it registers, none for the register check. -var firstCallOfEachCheck = []string{"", "Routes", "PublicPaths", "Stop before any Start", "the first Start"} +var firstCallOfEachCheck = []string{ + "", "Routes", "PublicPaths", "Stop before any Start", "the first Start", "the first Start", +} // fakeDeps is what a plugin checks scenario lends each Register: the count of dependencies built, this one included. type fakeDeps struct{ buildNumber int } @@ -72,10 +76,11 @@ type pluginChecksWorld struct { // fakePlugin is the plugin each Register of a plugin checks scenario builds, whose calls run the scenario's faults. type fakePlugin struct { - world *pluginChecksWorld - id string - startCount int - firstCall string + world *pluginChecksWorld + id string + startCount int + stopCountSinceStart int + firstCall string // routesLock is the lock Routes and PublicPaths take, and nil when the scenario gives the plugin none. routesLock chan struct{} } @@ -108,20 +113,23 @@ func (p *fakePlugin) noteFirstCall(call string) { p.firstCall = cmp.Or(p.firstCall, call) } -// startCallName counts one more Start of the plugin and returns the words naming it. +// startCallName counts one more Start of the plugin, with no Stop since, and returns the words naming it. func (p *fakePlugin) startCallName() string { p.world.mu.Lock() defer p.world.mu.Unlock() name := startCallNames[p.startCount] p.startCount++ + p.stopCountSinceStart = 0 return name } -// stopCallName returns the words naming a Stop of the plugin after the Starts it ran. +// stopCallName counts one more Stop of the plugin and returns the words naming it after the Starts and Stops it ran. func (p *fakePlugin) stopCallName() string { p.world.mu.Lock() defer p.world.mu.Unlock() - return stopCallNames[p.startCount] + name := stopCallNames[p.startCount][p.stopCountSinceStart] + p.stopCountSinceStart++ + return name } // fakePluginWithRoutes is a fake plugin with routes and public paths. diff --git a/pluginkit/plugintest/lifecycle.go b/pluginkit/plugintest/lifecycle.go index e6a2974..fe298b6 100644 --- a/pluginkit/plugintest/lifecycle.go +++ b/pluginkit/plugintest/lifecycle.go @@ -27,12 +27,14 @@ const ( // fixStartStopAgain is the fix of a Start or a Stop that broke its promise in the Start, Stop, Start, Stop run. fixStartStopAgain = "Let Start open again what Stop released, " + "and let each call return by the time its context ends." + // fixStopTwice is the fix of a second Stop that broke its promise after one Start. + fixStopTwice = "Let a second Stop find nothing left to release and return nil." ) // checks are the checks of the plugin contract in order, each run on a new plugin whose Register kept its promises. var checks = []func(plugin pluginkit.Plugin, stepBudget time.Duration) []Finding{ noFindingsPastRegister, routesBeforeStartFindings, publicPathsBeforeStartFindings, stopWithoutStartFindings, - startStopAgainFindings, + startStopAgainFindings, stopTwiceFindings, } // LifecycleFindings registers a new plugin from newDeps for each check and returns each promise the plugin breaks. @@ -158,12 +160,30 @@ func startStopAgainFindings(plugin pluginkit.Plugin, stepBudget time.Duration) [ {name: "the second Start", method: plugin.Start}, {name: "the second Stop", method: plugin.Stop}, } + return findingsOf(RuleStartStopAgain, fixStartStopAgain, firstProblemOf(calls, stepBudget)) +} + +// stopTwiceFindings returns the finding of a second Stop that fails after a Start and a Stop that kept their promises. +func stopTwiceFindings(plugin pluginkit.Plugin, stepBudget time.Duration) []Finding { + callsBeforeSecondStop := []lifecycleCall{ + {name: "the first Start", method: plugin.Start}, + {name: "the first Stop", method: plugin.Stop}, + } + if firstProblemOf(callsBeforeSecondStop, stepBudget) != "" { + return nil + } + secondStop := lifecycleCall{name: "the second of two Stops", method: plugin.Stop} + return findingsOf(RuleStopTwice, fixStopTwice, secondStop.problem(stepBudget)) +} + +// firstProblemOf makes calls in order until one breaks its promise, and returns that promise, or "" when none breaks. +func firstProblemOf(calls []lifecycleCall, stepBudget time.Duration) string { for _, call := range calls { if problem := call.problem(stepBudget); problem != "" { - return findingsOf(RuleStartStopAgain, fixStartStopAgain, problem) + return problem } } - return nil + return "" } // lifecycleCall is one Start or Stop a check makes, with the name its problem gives it. diff --git a/pluginkit/plugintest/lifecycle_test.go b/pluginkit/plugintest/lifecycle_test.go index f8542c4..6c64105 100644 --- a/pluginkit/plugintest/lifecycle_test.go +++ b/pluginkit/plugintest/lifecycle_test.go @@ -40,8 +40,13 @@ const ( secondStartName = "the second Start" // secondStopName is the name the checks give the Stop after the second Start. secondStopName = "the second Stop" + // secondOfTwoStopsName is the name the checks give a second Stop after one Start. + secondOfTwoStopsName = "the second of two Stops" ) +// stopNames are the names the checks give each Stop, by the count of Starts before it, then the count of Stops since. +var stopNames = [][]string{{stopBeforeStartName}, {firstStopName, secondOfTwoStopsName}, {secondStopName}} + // fault is how one call of a fake plugin breaks its promise, its zero value a call that keeps it. type fault struct { // err is the error the call answers. @@ -180,8 +185,9 @@ type fakePlugin struct { factory *fakePluginFactory depsNumber int - mu sync.Mutex - startCount int + mu sync.Mutex + startCount int + stopCountSinceStart int } // ID returns the id the factory's plugins call themselves, once its fault is applied. @@ -200,19 +206,22 @@ func (p *fakePlugin) Stop(ctx context.Context) error { return p.answerLifecycleCall(ctx, p.stopName()) } -// startName returns the name the checks give this plugin's next Start, counting it. +// startName returns the name the checks give this plugin's next Start, counting it with no Stop since. func (p *fakePlugin) startName() string { p.mu.Lock() defer p.mu.Unlock() p.startCount++ + p.stopCountSinceStart = 0 return [...]string{1: firstStartName, 2: secondStartName}[p.startCount] } -// stopName returns the name the checks give a Stop of this plugin after its Starts so far. +// stopName returns the name the checks give this plugin's next Stop after its Starts and Stops so far, counting it. func (p *fakePlugin) stopName() string { p.mu.Lock() defer p.mu.Unlock() - return [...]string{stopBeforeStartName, firstStopName, secondStopName}[p.startCount] + name := stopNames[p.startCount][p.stopCountSinceStart] + p.stopCountSinceStart++ + return name } // answerLifecycleCall records the Start or Stop named name and its context, then answers the error of its fault. @@ -367,6 +376,11 @@ func startStopAgainFinding(problem string) plugintest.Finding { "Let Start open again what Stop released, and let each call return by the time its context ends.") } +// stopTwiceFinding returns the stop-twice finding with problem. +func stopTwiceFinding(problem string) plugintest.Finding { + return finding("stop-twice", problem, "Let a second Stop find nothing left to release and return nil.") +} + // wantFindings checks that got holds exactly want, in order. func wantFindings(t *testing.T, got, want []plugintest.Finding) { t.Helper() @@ -383,15 +397,27 @@ func wantCalls(t *testing.T, factory *fakePluginFactory, want []string) { } } -// everyCall is each call the checks make of plugins that keep every promise, in order. -var everyCall = []string{ +// callsBeforeStartStopAgain is each call the checks before start-stop-again make of plugins that keep every promise. +var callsBeforeStartStopAgain = []string{ "newDeps 1", "Register of deps 1", "newDeps 2", "Register of deps 2", "Routes before Start of plugin 2", "newDeps 3", "Register of deps 3", "PublicPaths before Start of plugin 3", "newDeps 4", "Register of deps 4", "Stop before any Start of plugin 4", +} + +// everyCall is each call the checks make of plugins that keep every promise, in order. +var everyCall = slices.Concat(callsBeforeStartStopAgain, []string{ "newDeps 5", "Register of deps 5", "the first Start of plugin 5", "the first Stop of plugin 5", "the second Start of plugin 5", "the second Stop of plugin 5", -} + "newDeps 6", "Register of deps 6", "the first Start of plugin 6", "the first Stop of plugin 6", + "the second of two Stops of plugin 6", +}) + +// callsWhenEachFirstStartFails is each call the checks make of plugins whose every first Start breaks its promise. +var callsWhenEachFirstStartFails = slices.Concat(callsBeforeStartStopAgain, []string{ + "newDeps 5", "Register of deps 5", "the first Start of plugin 5", + "newDeps 6", "Register of deps 6", "the first Start of plugin 6", +}) func TestLifecycleFindingsAnswersNilForAPluginThatKeepsEveryPromise(t *testing.T) { t.Parallel() @@ -585,6 +611,12 @@ func TestLifecycleFindingsNamesABrokenPromiseOfEachStartAndStopOfTheRunUnderItsR wantOneFindingForEachCase(t, cases) } +func TestLifecycleFindingsNamesABrokenPromiseOfASecondStopAfterOneStartUnderItsRule(t *testing.T) { + t.Parallel() + + wantOneFindingForEachCase(t, failureCases(secondOfTwoStopsName, stopTwiceFinding)) +} + func TestLifecycleFindingsGivesNoHandlerForARoutesThatAnswersANilFunctionMapSliceOrChannel(t *testing.T) { t.Parallel() @@ -627,11 +659,14 @@ func TestLifecycleFindingsRunsEachCheckOnAPluginOfItsOwnFromDepsOfItsOwn(t *test func(factory *fakePluginFactory) { factory.faults[firstStopName] = fault{err: errors.New("already closed")} }, - everyCall[:len(everyCall)-2], + slices.Concat(callsBeforeStartStopAgain, []string{ + "newDeps 5", "Register of deps 5", "the first Start of plugin 5", "the first Stop of plugin 5", + "newDeps 6", "Register of deps 6", "the first Start of plugin 6", "the first Stop of plugin 6", + }), }, "a plugin whose first Start panics": { func(factory *fakePluginFactory) { factory.faults[firstStartName] = fault{panicValue: "boom"} }, - everyCall[:len(everyCall)-3], + callsWhenEachFirstStartFails, }, } for name, tc := range tests { @@ -657,6 +692,7 @@ func TestLifecycleFindingsKeepsOneBrokenPromiseFromHidingAnother(t *testing.T) { factory.faults[publicPathsName] = fault{panicValue: "boom"} factory.faults[stopBeforeStartName] = fault{err: errors.New("nothing to close")} factory.faults[secondStartName] = fault{err: errors.New("already started")} + factory.faults[secondOfTwoStopsName] = fault{err: errors.New("already closed")} findings := factory.lifecycleFindings() @@ -665,6 +701,7 @@ func TestLifecycleFindingsKeepsOneBrokenPromiseFromHidingAnother(t *testing.T) { routesFinding("PublicPaths before Start panicked: boom"), stopWithoutStartFinding("Stop before any Start answered the error: nothing to close"), startStopAgainFinding("the second Start answered the error: already started"), + stopTwiceFinding("the second of two Stops answered the error: already closed"), }) }) } @@ -679,14 +716,14 @@ func TestLifecycleFindingsCutsACallThatNeverReturnsAtTheStepBudgetAndRunsTheLate findings := factory.lifecycleFindings() - if waitTime := time.Since(callTime); waitTime != 2*stepBudget { - t.Errorf("the checks took %v, want two step budgets of %v", waitTime, stepBudget) + if waitTime := time.Since(callTime); waitTime != 3*stepBudget { + t.Errorf("the checks took %v, want three step budgets of %v", waitTime, stepBudget) } wantFindings(t, findings, []plugintest.Finding{ routesFinding("Routes before Start did not return within 50ms"), startStopAgainFinding("the first Start did not return within 50ms"), }) - wantCalls(t, factory, everyCall[:len(everyCall)-3]) + wantCalls(t, factory, callsWhenEachFirstStartFails) }) } @@ -720,8 +757,8 @@ func TestLifecycleFindingsNeverBlocksACallThatReturnsAfterItsCheckEnded(t *testi wantFindings(t, findings, []plugintest.Finding{ startStopAgainFinding("the first Start did not return within 50ms"), }) - wantCalls(t, factory, - append(slices.Clone(everyCall[:len(everyCall)-3]), "the first Start returned after the release")) + wantCalls(t, factory, append(slices.Clone(callsWhenEachFirstStartFails), + "the first Start returned after the release", "the first Start returned after the release")) }) } @@ -744,6 +781,7 @@ func TestLifecycleFindingsHandsEachStartAndStopAContextOfItsOwnThatEndsAtTheStep } if want := []string{ stopBeforeStartName, firstStartName, firstStopName, secondStartName, secondStopName, + firstStartName, firstStopName, secondOfTwoStopsName, }; !slices.Equal(names, want) { t.Errorf("calls with a context = %q, want %q", names, want) } diff --git a/pluginkit/plugintest/plugintest.go b/pluginkit/plugintest/plugintest.go index c94e084..fc54120 100644 --- a/pluginkit/plugintest/plugintest.go +++ b/pluginkit/plugintest/plugintest.go @@ -21,4 +21,6 @@ const ( RuleStopWithoutStart = "stop-without-start" // RuleStartStopAgain is the rule that Start, Stop, Start and Stop each return nil within the step budget. RuleStartStopAgain = "start-stop-again" + // RuleStopTwice is the rule that a second Stop after one Start returns nil within the step budget. + RuleStopTwice = "stop-twice" ) From 883dd183a13da62a35af3886bc9e8ad1f2db7b90 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Mon, 30 Nov 2026 00:06:04 +0100 Subject: [PATCH 11/11] fix(pluginkit): name a Start or Stop that fails before a second Stop, once --- pluginkit/features/plugin-checks.feature | 15 ++++- .../features/steps_plugin_checks_test.go | 64 +++++++++++++------ pluginkit/plugintest/lifecycle.go | 21 ++++-- pluginkit/plugintest/lifecycle_test.go | 56 ++++++++++++++++ 4 files changed, 129 insertions(+), 27 deletions(-) diff --git a/pluginkit/features/plugin-checks.feature b/pluginkit/features/plugin-checks.feature index 11645d0..285a8b6 100644 --- a/pluginkit/features/plugin-checks.feature +++ b/pluginkit/features/plugin-checks.feature @@ -8,9 +8,10 @@ Feature: Checking the promises a plugin makes to its host from its own tests Each check registers a new plugin from new dependencies, so one broken promise does not hide another, and a call that never returns is cut at the time limit. A Start or a Stop that fails before a second Stop is - named once, under start-stop-again. Each finding names its rule, the - problem and the fix. An application can also check one manifest's id - against the ids it reserves and the names the generated wiring uses. + named under start-stop-again, and a finding two checks give alike is + named once. Each finding names its rule, the problem and the fix. An + application can also check one manifest's id against the ids it + reserves and the names the generated wiring uses. Scenario: A plugin that keeps every promise gives no finding Given the plugin "events" keeps every promise @@ -77,6 +78,14 @@ Feature: Checking the promises a plugin makes to its host from its own tests | stop-twice | the second of two Stops answered the error: already closed | And every Register of "events" received dependencies built for it alone + Scenario: A Start that fails only on the plugin of a later check is still named + Given the plugin "events" keeps its port after Stop + When the application checks the lifecycle of "events" with a time limit of 200ms + Then the check gives these findings, in this order: + | rule | problem | + | start-stop-again | the second Start answered the error: port in use | + | start-stop-again | the first Start answered the error: port in use | + Scenario: A call that never returns is cut at the time limit and the later checks still run Given the plugin "events" never returns from Routes And the plugin "events" answers the error "already started" from the second Start diff --git a/pluginkit/features/steps_plugin_checks_test.go b/pluginkit/features/steps_plugin_checks_test.go index 548f63c..933b779 100644 --- a/pluginkit/features/steps_plugin_checks_test.go +++ b/pluginkit/features/steps_plugin_checks_test.go @@ -54,24 +54,26 @@ type startStopCall struct { // pluginChecksWorld is what one scenario of the plugin checks feature fakes, records and finds. type pluginChecksWorld struct { - mu sync.Mutex - endOfScenario chan struct{} - pluginID string - claimedID string - hasRoutes bool - hasRoutesLock bool - answersNoPlugin bool - answersNoHandler bool - faults map[string]func() - callErrors map[string]error - builtDeps []fakeDeps - receivedDeps []fakeDeps - plugins []*fakePlugin - startStopCalls []startStopCall - findings []plugintest.Finding - manifest wire.Manifest - reservedIDs []string - idCheckErr error + mu sync.Mutex + endOfScenario chan struct{} + pluginID string + claimedID string + hasRoutes bool + hasRoutesLock bool + keepsPortAfterStop bool + isPortInUse bool + answersNoPlugin bool + answersNoHandler bool + faults map[string]func() + callErrors map[string]error + builtDeps []fakeDeps + receivedDeps []fakeDeps + plugins []*fakePlugin + startStopCalls []startStopCall + findings []plugintest.Finding + manifest wire.Manifest + reservedIDs []string + idCheckErr error } // fakePlugin is the plugin each Register of a plugin checks scenario builds, whose calls run the scenario's faults. @@ -90,11 +92,14 @@ func (p *fakePlugin) ID() string { return p.id } -// Start notes the call and its context, then runs the fault of the first or the second Start and answers its error. +// Start notes the call and its context, takes the port the scenario gives, then answers the error of this Start. func (p *fakePlugin) Start(ctx context.Context) error { call := p.startCallName() p.noteFirstCall(call) p.world.recordCall(ctx, "Start") + if err := p.world.takePort(); err != nil { + return err + } return p.world.answerCall(call) } @@ -171,6 +176,20 @@ func (w *pluginChecksWorld) recordCall(ctx context.Context, method string) { w.startStopCalls = append(w.startStopCalls, call) } +// takePort marks the port in use when the plugin keeps it after Stop, answering an error when it is in use already. +func (w *pluginChecksWorld) takePort() error { + w.mu.Lock() + defer w.mu.Unlock() + if !w.keepsPortAfterStop { + return nil + } + if w.isPortInUse { + return errors.New("port in use") + } + w.isPortInUse = true + return nil +} + // runFault runs the fault the scenario gives the call these words name, if it gives one. func (w *pluginChecksWorld) runFault(call string) { w.mu.Lock() @@ -254,6 +273,12 @@ func (w *pluginChecksWorld) addRoutesLock(id string) { w.hasRoutesLock = true } +// keepPortAfterStop names the fake plugin id and has each Start take one port that no Stop releases. +func (w *pluginChecksWorld) keepPortAfterStop(id string) { + w.pluginID = id + w.keepsPortAfterStop = true +} + // answerError names the fake plugin id and has the call these words name answer an error with text. func (w *pluginChecksWorld) answerError(id, text, call string) { w.pluginID = id @@ -457,6 +482,7 @@ func givenPluginChecks(sc *godog.ScenarioContext, w *pluginChecksWorld) { sc.Step(`^the plugin "([^"]*)" keeps every promise$`, w.keepEveryPromise) sc.Step(`^the plugin "([^"]*)" has no routes and no public paths$`, w.leaveOutRoutes) sc.Step(`^the plugin "([^"]*)" guards Routes and PublicPaths with one lock$`, w.addRoutesLock) + sc.Step(`^the plugin "([^"]*)" keeps its port after Stop$`, w.keepPortAfterStop) sc.Step(`^the plugin "([^"]*)" answers the error "([^"]*)" from (`+errorCallsPattern+`)$`, w.answerError) sc.Step(`^the plugin "([^"]*)" panics with "([^"]*)" in (`+callsPattern+`)$`, w.panicIn) sc.Step(`^the plugin "([^"]*)" never returns from (`+callsPattern+`)$`, w.blockCall) diff --git a/pluginkit/plugintest/lifecycle.go b/pluginkit/plugintest/lifecycle.go index fe298b6..ef069e8 100644 --- a/pluginkit/plugintest/lifecycle.go +++ b/pluginkit/plugintest/lifecycle.go @@ -6,6 +6,7 @@ import ( "context" "fmt" "net/http" + "slices" "time" "github.com/gopherium/framework/pluginkit" @@ -37,7 +38,7 @@ var checks = []func(plugin pluginkit.Plugin, stepBudget time.Duration) []Finding startStopAgainFindings, stopTwiceFindings, } -// LifecycleFindings registers a new plugin from newDeps for each check and returns each promise the plugin breaks. +// LifecycleFindings registers a new plugin from newDeps for each check and returns each promise it breaks, once. func LifecycleFindings[D any, P pluginkit.Plugin]( registration pluginkit.Registration[D, P], newDeps func() D, stepBudget time.Duration, ) []Finding { @@ -47,7 +48,17 @@ func LifecycleFindings[D any, P pluginkit.Plugin]( if registerFinding != nil { return append(findings, *registerFinding) } - findings = append(findings, check(plugin, stepBudget)...) + findings = appendOnce(findings, check(plugin, stepBudget)) + } + return findings +} + +// appendOnce appends to findings each finding of checkFindings that findings does not hold yet. +func appendOnce(findings, checkFindings []Finding) []Finding { + for _, checkFinding := range checkFindings { + if !slices.Contains(findings, checkFinding) { + findings = append(findings, checkFinding) + } } return findings } @@ -163,14 +174,14 @@ func startStopAgainFindings(plugin pluginkit.Plugin, stepBudget time.Duration) [ return findingsOf(RuleStartStopAgain, fixStartStopAgain, firstProblemOf(calls, stepBudget)) } -// stopTwiceFindings returns the finding of a second Stop that fails after a Start and a Stop that kept their promises. +// stopTwiceFindings starts a plugin and stops it twice, naming a failing Start or first Stop under start-stop-again. func stopTwiceFindings(plugin pluginkit.Plugin, stepBudget time.Duration) []Finding { callsBeforeSecondStop := []lifecycleCall{ {name: "the first Start", method: plugin.Start}, {name: "the first Stop", method: plugin.Stop}, } - if firstProblemOf(callsBeforeSecondStop, stepBudget) != "" { - return nil + if problem := firstProblemOf(callsBeforeSecondStop, stepBudget); problem != "" { + return findingsOf(RuleStartStopAgain, fixStartStopAgain, problem) } secondStop := lifecycleCall{name: "the second of two Stops", method: plugin.Stop} return findingsOf(RuleStopTwice, fixStopTwice, secondStop.problem(stepBudget)) diff --git a/pluginkit/plugintest/lifecycle_test.go b/pluginkit/plugintest/lifecycle_test.go index 6c64105..e3b18b0 100644 --- a/pluginkit/plugintest/lifecycle_test.go +++ b/pluginkit/plugintest/lifecycle_test.go @@ -310,6 +310,23 @@ func (p routesLockPlugin) PublicPaths() []string { return []string{"/feed.xml"} } +// lifecycleErrorPlugin is a plugin held by value whose Start and Stop answer the errors it holds. +type lifecycleErrorPlugin struct { + valuePlugin + startErr error + stopErr error +} + +// Start answers the plugin's Start error. +func (p lifecycleErrorPlugin) Start(context.Context) error { + return p.startErr +} + +// Stop answers the plugin's Stop error. +func (p lifecycleErrorPlugin) Stop(context.Context) error { + return p.stopErr +} + // mapHandler is a handler whose type is a map. type mapHandler map[string]string @@ -617,6 +634,45 @@ func TestLifecycleFindingsNamesABrokenPromiseOfASecondStopAfterOneStartUnderItsR wantOneFindingForEachCase(t, failureCases(secondOfTwoStopsName, stopTwiceFinding)) } +func TestLifecycleFindingsNamesAStartOrAStopThatFailsOnlyBeforeASecondStopUnderStartStopAgain(t *testing.T) { + t.Parallel() + + tests := map[string]struct { + stopTwicePlugin lifecycleErrorPlugin + want plugintest.Finding + }{ + "a Start": { + lifecycleErrorPlugin{startErr: errors.New("port in use")}, + startStopAgainFinding("the first Start answered the error: port in use"), + }, + "a Stop": { + lifecycleErrorPlugin{stopErr: errors.New("already closed")}, + startStopAgainFinding("the first Stop answered the error: already closed"), + }, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + runWithFakePluginFactory(t, func(t *testing.T, factory *fakePluginFactory) { + registration := pluginkit.Registration[fakeDeps, pluginkit.Plugin]{ + ID: "events", + Register: func(deps fakeDeps) (pluginkit.Plugin, error) { + if deps.callNumber == 6 { + return tc.stopTwicePlugin, nil + } + return factory.register(deps) + }, + } + + findings := plugintest.LifecycleFindings(registration, factory.newDeps, stepBudget) + + wantFindings(t, findings, []plugintest.Finding{tc.want}) + }) + }) + } +} + func TestLifecycleFindingsGivesNoHandlerForARoutesThatAnswersANilFunctionMapSliceOrChannel(t *testing.T) { t.Parallel()