From cd55a3980d5619055f87f8a5701e5e91efa8d643 Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Wed, 18 Nov 2026 20:04:47 +0100 Subject: [PATCH] docs(pier,seaglass,sunrise,sunscreen,tide): compile README Go examples via src= (quick-261118-qsd) --- modules/pier/README.md | 84 ++++++++++---- modules/seaglass/README.md | 26 ++++- modules/seaglass/example_test.go | 33 ++++++ modules/sunrise/README.md | 10 +- modules/sunrise/example_test.go | 35 ++++++ modules/sunscreen/README.md | 29 +++-- modules/sunscreen/example_test.go | 52 +++++++++ modules/tide/README.md | 64 ++++++----- modules/tide/example_test.go | 185 ++++++++++++++++++++++++++++++ 9 files changed, 449 insertions(+), 69 deletions(-) create mode 100644 modules/seaglass/example_test.go create mode 100644 modules/sunrise/example_test.go diff --git a/modules/pier/README.md b/modules/pier/README.md index 3a723f6b..2c80d593 100644 --- a/modules/pier/README.md +++ b/modules/pier/README.md @@ -49,27 +49,71 @@ Use cases: ## Usage -Declare a tool in a plugin (the `pact` types only; no SDK import): +Declare tools and prompts in a plugin (the `pact` types only; no SDK import). The plugin's `MCP` method returns this declaration: -```go -type createPostInput struct { - Title string `json:"title" jsonschema:"the post title"` - Body string `json:"body" jsonschema:"the Markdown body"` - Published bool `json:"published,omitempty" jsonschema:"publish at once"` -} - -type showPostInput struct { - ID int `json:"id" path:"id" jsonschema:"the post id"` -} - -func (p Plugin) MCP() pact.MCP { - return pact.MCP{Tools: []pact.MCPTool{ - {Name: "create_post", Title: "Create post", Description: "Creates a draft post.", - Guard: "backend", Method: "POST", Path: "/_blog/api/v1/posts", Input: createPostInput{}, - Permissions: []string{"acme.blog.access_posts"}}, - {Name: "show_post", Title: "Show post", Description: "Shows one post.", - Method: "GET", Path: "/_blog/api/v1/posts/{id}", Input: showPostInput{}}, - }} +```go src=modules/pier/example_mcp_test.go#blogTools +// blogTools is the MCP declaration of the acme.blog plugin. A field of an +// input struct is a body field unless its path or query tag says +// otherwise; fields without omitempty are required in the schema. +func blogTools() pact.MCP { + type createPostInput struct { + Title string `json:"title" jsonschema:"the post title"` + Body string `json:"body" jsonschema:"the Markdown body"` + Published bool `json:"published,omitempty" jsonschema:"publish at once instead of saving a draft"` + } + type showPostInput struct { + ID int `json:"id" path:"id" jsonschema:"the post id"` + } + type listPostsInput struct { + Query string `json:"q,omitempty" query:"q" jsonschema:"a phrase the title or body contains"` + } + return pact.MCP{ + Tools: []pact.MCPTool{ + { + // Exposed as blog_create_post; the backend guard runs it as + // the linked administrator, listed only with access_posts. + Name: "create_post", + Title: "Create post", + Description: "Creates a post; a draft unless published is true.", + Guard: "backend", + Method: "POST", + Path: "/_blog/api/v1/posts", + Input: createPostInput{}, + Permissions: []string{"acme.blog.access_posts"}, + }, + { + // Exposed as blog_show_post; the route's user.api_token + // middleware names the guard, GET makes it read-only. + Name: "show_post", + Title: "Show post", + Description: "Shows one post by id.", + Method: "GET", + Path: "/_blog/api/v1/posts/{id}", + Input: showPostInput{}, + }, + { + Name: "list_posts", + Title: "List posts", + Description: "Lists posts, optionally those matching a phrase.", + Method: "GET", + Path: "/_blog/api/v1/posts", + Input: listPostsInput{}, + }, + }, + Prompts: []pact.MCPPrompt{ + { + // Exposed as blog_summarize; prompts name their guard. + Name: "summarize", + Title: "Summarize a post", + Description: "Asks for a three-sentence summary of a post.", + Guard: "user", + Arguments: []pact.MCPPromptArgument{{Name: "slug", Description: "the post slug", Required: true}}, + Render: func(_ context.Context, args map[string]string) ([]pact.MCPPromptMessage, error) { + return []pact.MCPPromptMessage{{Role: "user", Text: "Summarize the post " + args["slug"] + " in three sentences."}}, nil + }, + }, + }, + } } ``` diff --git a/modules/seaglass/README.md b/modules/seaglass/README.md index b4e6d22a..3253742a 100644 --- a/modules/seaglass/README.md +++ b/modules/seaglass/README.md @@ -31,14 +31,30 @@ Use cases: ## Usage -```go +```go src=modules/seaglass/example_test.go#ExampleSanitizeReport clean, report := seaglass.SanitizeReport(`

Hi

`) -// clean == "

Hi

" -// report.Elements == []string{"script"}, report.Attributes == []string{"onclick"} +fmt.Println(clean) +fmt.Println(report.Elements, report.Attributes, report.Changed) +// Output: +//

Hi

+// [script] [onclick] true +``` -if err := seaglass.Check(stored); err != nil { - // stored HTML would change under the policy +```go src=modules/seaglass/example_test.go#ExampleCheck +for _, stored := range []string{ + `

Hi call

`, + `

x

`, +} { + if err := seaglass.Check(stored); err != nil { + // stored HTML would change under the policy + fmt.Println(err) + continue + } + fmt.Println("kept whole") } +// Output: +// kept whole +// seaglass: HTML contains elements, attributes or URLs that are not allowed ``` ## API reference diff --git a/modules/seaglass/example_test.go b/modules/seaglass/example_test.go new file mode 100644 index 00000000..d5abab4d --- /dev/null +++ b/modules/seaglass/example_test.go @@ -0,0 +1,33 @@ +package seaglass_test + +import ( + "fmt" + + "git.golem15.com/golem15/summercms/modules/seaglass" +) + +func ExampleSanitizeReport() { + clean, report := seaglass.SanitizeReport(`

Hi

`) + fmt.Println(clean) + fmt.Println(report.Elements, report.Attributes, report.Changed) + // Output: + //

Hi

+ // [script] [onclick] true +} + +func ExampleCheck() { + for _, stored := range []string{ + `

Hi call

`, + `

x

`, + } { + if err := seaglass.Check(stored); err != nil { + // stored HTML would change under the policy + fmt.Println(err) + continue + } + fmt.Println("kept whole") + } + // Output: + // kept whole + // seaglass: HTML contains elements, attributes or URLs that are not allowed +} diff --git a/modules/sunrise/README.md b/modules/sunrise/README.md index 1eb41c55..37052a4a 100644 --- a/modules/sunrise/README.md +++ b/modules/sunrise/README.md @@ -71,15 +71,7 @@ Update mode takes no other argument. It works the same from bash, zsh and fish, Serving the script from a Go handler: -```go -package acme - -import ( - "net/http" - - "git.golem15.com/golem15/summercms/modules/sunrise" -) - +```go src=modules/sunrise/example_test.go#newScript func newScript(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Header().Set("X-Content-Type-Options", "nosniff") diff --git a/modules/sunrise/example_test.go b/modules/sunrise/example_test.go new file mode 100644 index 00000000..56d52e1a --- /dev/null +++ b/modules/sunrise/example_test.go @@ -0,0 +1,35 @@ +package sunrise_test + +import ( + "bytes" + "fmt" + "net/http" + "net/http/httptest" + + "git.golem15.com/golem15/summercms/modules/sunrise" +) + +func newScript(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + w.Header().Set("X-Content-Type-Options", "nosniff") + _, _ = w.Write(sunrise.Script()) +} + +func Example() { + srv := httptest.NewServer(http.HandlerFunc(newScript)) + defer srv.Close() + + resp, err := http.Get(srv.URL + "/new") + if err != nil { + fmt.Println(err) + return + } + defer resp.Body.Close() + var body bytes.Buffer + _, _ = body.ReadFrom(resp.Body) + fmt.Println(resp.StatusCode, resp.Header.Get("Content-Type")) + fmt.Println(bytes.Equal(body.Bytes(), sunrise.Script()), bytes.HasPrefix(body.Bytes(), []byte("#!"))) + // Output: + // 200 text/plain; charset=utf-8 + // true true +} diff --git a/modules/sunscreen/README.md b/modules/sunscreen/README.md index 9b65c973..b3be4894 100644 --- a/modules/sunscreen/README.md +++ b/modules/sunscreen/README.md @@ -30,21 +30,34 @@ Use cases: ## Usage -A program that does not use diary installs it as the default logger: +A program that does not use diary installs it as the default logger when it starts: -```go -func main() { - sunscreen.InstallDefault(os.Stderr) - // ... +```go src=modules/sunscreen/example_test.go#startLogging +// startLogging is the first thing the main function of a program that does +// not use diary runs; main passes os.Stderr. +func startLogging(stderr io.Writer) { + sunscreen.InstallDefault(stderr) + slog.Info("starting", "token", "abc123") + log.Print("calling the vendor with Authorization: Bearer abc.def") } ``` To redact another handler, for example a JSON handler in a custom binary, wrap it: -```go -logger := slog.New(sunscreen.Wrap(slog.NewJSONHandler(os.Stderr, nil))) +```go src=modules/sunscreen/example_test.go#ExampleWrap_json +// Drop the time so the output is stable; a real application keeps it. +opts := &slog.HandlerOptions{ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { + if len(groups) == 0 && a.Key == slog.TimeKey { + return slog.Attr{} + } + return a +}} +key, err := "live-key-123", errors.New("401 Unauthorized") + +logger := slog.New(sunscreen.Wrap(slog.NewJSONHandler(os.Stdout, opts))) logger.Error("vendor call failed", "api_key", key, "err", err) -// {"level":"ERROR","msg":"vendor call failed","api_key":"[REDACTED]","err":"..."} +// Output: +// {"level":"ERROR","msg":"vendor call failed","api_key":"[REDACTED]","err":"401 Unauthorized"} ``` Redaction is a safety net, not a licence: log ids and outcomes, never request bodies, tokens or arguments that carry them. diff --git a/modules/sunscreen/example_test.go b/modules/sunscreen/example_test.go index d5667b0b..368040e0 100644 --- a/modules/sunscreen/example_test.go +++ b/modules/sunscreen/example_test.go @@ -1,9 +1,14 @@ package sunscreen_test import ( + "bytes" "errors" + "io" + "log" "log/slog" "os" + "strings" + "testing" "git.golem15.com/golem15/summercms/modules/sunscreen" ) @@ -28,3 +33,50 @@ func ExampleWrap() { // Output: // level=INFO msg="vendor call failed" api_key=[REDACTED] request.Authorization=[REDACTED] err="401 for key sk-[REDACTED]" } + +func ExampleWrap_json() { + // Drop the time so the output is stable; a real application keeps it. + opts := &slog.HandlerOptions{ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { + if len(groups) == 0 && a.Key == slog.TimeKey { + return slog.Attr{} + } + return a + }} + key, err := "live-key-123", errors.New("401 Unauthorized") + + logger := slog.New(sunscreen.Wrap(slog.NewJSONHandler(os.Stdout, opts))) + logger.Error("vendor call failed", "api_key", key, "err", err) + // Output: + // {"level":"ERROR","msg":"vendor call failed","api_key":"[REDACTED]","err":"401 Unauthorized"} +} + +// startLogging is the first thing the main function of a program that does +// not use diary runs; main passes os.Stderr. +func startLogging(stderr io.Writer) { + sunscreen.InstallDefault(stderr) + slog.Info("starting", "token", "abc123") + log.Print("calling the vendor with Authorization: Bearer abc.def") +} + +// TestDocsInstallDefault runs startLogging into a buffer and restores the +// process default logger and the log package afterwards. +func TestDocsInstallDefault(t *testing.T) { + previous, out, flags := slog.Default(), log.Writer(), log.Flags() + t.Cleanup(func() { + slog.SetDefault(previous) + log.SetOutput(out) + log.SetFlags(flags) + }) + + var buf bytes.Buffer + startLogging(&buf) + got := buf.String() + for _, want := range []string{`msg=starting token=[REDACTED]`, `Authorization: Bearer [REDACTED]`} { + if !strings.Contains(got, want) { + t.Errorf("output %q lacks %q", got, want) + } + } + if strings.Contains(got, "abc123") || strings.Contains(got, "abc.def") { + t.Errorf("output leaks a secret: %q", got) + } +} diff --git a/modules/tide/README.md b/modules/tide/README.md index cb5df3fb..3dce8ba9 100644 --- a/modules/tide/README.md +++ b/modules/tide/README.md @@ -41,38 +41,48 @@ Use cases: Record a flow once against the reference backend, then replay it against the port: -```go -spec, err := tide.LoadFlow("testdata/parity/posts.spec.yaml") -if err != nil { - return err -} -flow, err := tide.RecordFlow(ctx, spec, tide.RecordConfig{Target: "http://127.0.0.1:8000"}) -if err != nil { - return err -} -if err := tide.SaveFlow("testdata/parity/posts.yaml", flow); err != nil { - return err -} - -res, err := tide.ReplayFlow(ctx, flow, tide.ReplayConfig{ - Target: "http://127.0.0.1:8080", - BaseDir: "testdata/parity", -}) -if err != nil { - return err -} -for _, step := range res.Steps { - for _, d := range step.Diffs { - fmt.Printf("%s %s: want %s, got %s\n", step.ID, d.Path, d.Expected, d.Actual) +```go src=modules/tide/example_test.go#parity +// parity records the flow spec kept in dir against the reference backend +// once, saves the recorded flow next to it, then replays it against the +// port and prints every difference to w. +func parity(ctx context.Context, dir, reference, port string, w io.Writer) error { + spec, err := tide.LoadFlow(filepath.Join(dir, "posts.spec.yaml")) + if err != nil { + return err } + flow, err := tide.RecordFlow(ctx, spec, tide.RecordConfig{Target: reference}) + if err != nil { + return err + } + if err := tide.SaveFlow(filepath.Join(dir, "posts.yaml"), flow); err != nil { + return err + } + + res, err := tide.ReplayFlow(ctx, flow, tide.ReplayConfig{ + Target: port, + BaseDir: dir, + }) + var mismatch *tide.MismatchError + if errors.As(err, &mismatch) { + res = mismatch.Result // a difference is an error carrying the result + } else if err != nil { + return err + } + for _, step := range res.Steps { + for _, d := range step.Diffs { + fmt.Fprintf(w, "%s %s: want %s, got %s\n", step.ID, d.Path, d.Expected, d.Actual) + } + } + return nil } ``` Record the publications a reference backend sends for one flow step, then compare a new backend's publications with them: -```go +```go src=modules/tide/example_test.go#broadcasts golden, err := tide.RecordBroadcasts(ctx, spec, tide.BroadcastConfig{ - Target: "http://127.0.0.1:8000", + Target: reference, // a loopback URL such as http://127.0.0.1:8000 + Listen: listen, // empty: tide.DefaultCentrifugoListen APIKey: "test-only-key", Store: store, Step: "delete", @@ -81,7 +91,7 @@ golden, err := tide.RecordBroadcasts(ctx, spec, tide.BroadcastConfig{ if err != nil { return err } -if err := tide.WriteBroadcastGolden("testdata/broadcasts/deleted.yaml", golden); err != nil { +if err := tide.WriteBroadcastGolden(filepath.Join(dir, "deleted.yaml"), golden); err != nil { return err } @@ -91,7 +101,7 @@ if err != nil { return err } for _, d := range tide.DiffPublications(golden.Publications, norm) { - fmt.Printf("%s: want %s, got %s\n", d.Path, d.Expected, d.Actual) + fmt.Fprintf(w, "%s: want %s, got %s\n", d.Path, d.Expected, d.Actual) } ``` diff --git a/modules/tide/example_test.go b/modules/tide/example_test.go index fb9fc627..bedc2048 100644 --- a/modules/tide/example_test.go +++ b/modules/tide/example_test.go @@ -1,12 +1,19 @@ package tide_test import ( + "bytes" "context" "errors" "fmt" + "io" + "net" "net/http" "net/http/httptest" "os" + "path/filepath" + "strings" + "testing" + "time" "git.golem15.com/golem15/summercms/modules/tide" ) @@ -67,3 +74,181 @@ func ExampleReplayFlow() { // ok: false // list-posts $.data[0].title: want "Hello", got "hello" } + +// parity records the flow spec kept in dir against the reference backend +// once, saves the recorded flow next to it, then replays it against the +// port and prints every difference to w. +func parity(ctx context.Context, dir, reference, port string, w io.Writer) error { + spec, err := tide.LoadFlow(filepath.Join(dir, "posts.spec.yaml")) + if err != nil { + return err + } + flow, err := tide.RecordFlow(ctx, spec, tide.RecordConfig{Target: reference}) + if err != nil { + return err + } + if err := tide.SaveFlow(filepath.Join(dir, "posts.yaml"), flow); err != nil { + return err + } + + res, err := tide.ReplayFlow(ctx, flow, tide.ReplayConfig{ + Target: port, + BaseDir: dir, + }) + var mismatch *tide.MismatchError + if errors.As(err, &mismatch) { + res = mismatch.Result // a difference is an error carrying the result + } else if err != nil { + return err + } + for _, step := range res.Steps { + for _, d := range step.Diffs { + fmt.Fprintf(w, "%s %s: want %s, got %s\n", step.ID, d.Path, d.Expected, d.Actual) + } + } + return nil +} + +// TestDocsParity runs parity on a spec written to a temporary directory, +// against two httptest backends whose titles differ. +func TestDocsParity(t *testing.T) { + spec, err := os.ReadFile("testdata/docs/posts-spec.yaml") + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "posts.spec.yaml"), spec, 0o644); err != nil { + t.Fatal(err) + } + reference := backend(`{"data":[{"id":12,"title":"Hello","created_at":"2026-09-30T10:00:00+00:00"}]}`) + defer reference.Close() + port := backend(`{"data":[{"id":3,"title":"hello","created_at":"2026-10-01T08:30:00+00:00"}]}`) + defer port.Close() + + var out bytes.Buffer + if err := parity(t.Context(), dir, reference.URL, port.URL, &out); err != nil { + t.Fatal(err) + } + if want := "list-posts $.data[0].title: want \"Hello\", got \"hello\"\n"; out.String() != want { + t.Fatalf("diffs = %q, want %q", out.String(), want) + } + if _, err := tide.LoadFlow(filepath.Join(dir, "posts.yaml")); err != nil { + t.Fatalf("recorded flow: %v", err) + } +} + +// broadcasts records the publications the reference backend sends for the +// delete step of spec, writes them as a golden in dir, and compares the +// publications a new backend sent to rec with it, printing the differences +// to w. listen is the recorder address the reference backend publishes to. +func broadcasts(ctx context.Context, spec tide.Flow, reference, listen string, store *tide.Store, dir string, + rec *tide.CentrifugoRecorder, idsOfTheNewBackend *tide.Store, w io.Writer) error { + // docs:start broadcasts + golden, err := tide.RecordBroadcasts(ctx, spec, tide.BroadcastConfig{ + Target: reference, // a loopback URL such as http://127.0.0.1:8000 + Listen: listen, // empty: tide.DefaultCentrifugoListen + APIKey: "test-only-key", + Store: store, + Step: "delete", + IDs: []string{"id:room", "id:item"}, + }) + if err != nil { + return err + } + if err := tide.WriteBroadcastGolden(filepath.Join(dir, "deleted.yaml"), golden); err != nil { + return err + } + + // Later, with the new backend publishing to rec (a tide.CentrifugoRecorder): + norm, err := tide.NormalizePublications(rec.Publications(), idsOfTheNewBackend) + if err != nil { + return err + } + for _, d := range tide.DiffPublications(golden.Publications, norm) { + fmt.Fprintf(w, "%s: want %s, got %s\n", d.Path, d.Expected, d.Actual) + } + // docs:end broadcasts + return nil +} + +// itemsBackend is a backend whose create and delete endpoints publish to +// the Centrifugo API at centrifugo, using the given ids and delete event. +func itemsBackend(centrifugo, room, item, deleted string) *httptest.Server { + publish := func(body string) { + req, _ := http.NewRequest(http.MethodPost, centrifugo+"/api/publish", strings.NewReader(body)) + req.Header.Set("Authorization", "apikey test-only-key") + if resp, err := http.DefaultClient.Do(req); err == nil { + _ = resp.Body.Close() + } + } + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + event := "created" + if r.Method == http.MethodDelete { + event = deleted + } + publish(`{"channel":"room:` + room + `","data":{"event":"` + event + `","payload":{"id":` + item + `},"timestamp":"2026-09-30T10:00:00+00:00"}}`) + if r.Method == http.MethodPost { + fmt.Fprint(w, `{"data":{"id":`+item+`}}`) + return + } + fmt.Fprint(w, `{"message":"deleted"}`) + })) +} + +// TestDocsBroadcasts records a golden from one backend and compares the +// publications of a second one, which renamed the delete event, with it. +func TestDocsBroadcasts(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + listen := ln.Addr().String() + _ = ln.Close() + reference := itemsBackend("http://"+listen, "5", "77", "deleted") + defer reference.Close() + + store, err := tide.OpenStore("") + if err != nil { + t.Fatal(err) + } + store.Set("id:room", "5") + spec := tide.Flow{Version: tide.CurrentVersion, Name: "items", Steps: []tide.Step{ + {ID: "create", Request: tide.Request{Method: "POST", Path: "/items"}, + Capture: []tide.CaptureRule{{From: "response.json", Path: "$.data.id", As: "id:item"}}}, + {ID: "delete", Request: tide.Request{Method: "DELETE", Path: "/items/{{id:item}}"}}, + }} + + // The new backend publishes to rec with its own ids. + rec := tide.NewCentrifugoRecorder(tide.CentrifugoRecorderOptions{APIKey: "test-only-key"}) + centrifugo := httptest.NewServer(rec) + defer centrifugo.Close() + port := itemsBackend(centrifugo.URL, "9", "31", "removed") + defer port.Close() + req, _ := http.NewRequest(http.MethodDelete, port.URL+"/items/31", nil) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + ids, err := tide.OpenStore("") + if err != nil { + t.Fatal(err) + } + ids.Set("id:room", "9") + ids.Set("id:item", "31") + + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + dir := t.TempDir() + var out bytes.Buffer + if err := broadcasts(ctx, spec, reference.URL, listen, store, dir, rec, ids, &out); err != nil { + t.Fatal(err) + } + if want := `$[0].body.data.event: want "deleted", got "removed"` + "\n"; out.String() != want { + t.Fatalf("diffs = %q, want %q", out.String(), want) + } + if _, err := tide.LoadBroadcastGolden(filepath.Join(dir, "deleted.yaml")); err != nil { + t.Fatalf("golden: %v", err) + } +}