docs(pier,seaglass,sunrise,sunscreen,tide): compile README Go examples via src= (quick-261118-qsd)
This commit is contained in:
@@ -49,27 +49,71 @@ Use cases:
|
|||||||
|
|
||||||
## Usage
|
## 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
|
```go src=modules/pier/example_mcp_test.go#blogTools
|
||||||
type createPostInput struct {
|
// 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"`
|
Title string `json:"title" jsonschema:"the post title"`
|
||||||
Body string `json:"body" jsonschema:"the Markdown body"`
|
Body string `json:"body" jsonschema:"the Markdown body"`
|
||||||
Published bool `json:"published,omitempty" jsonschema:"publish at once"`
|
Published bool `json:"published,omitempty" jsonschema:"publish at once instead of saving a draft"`
|
||||||
}
|
}
|
||||||
|
type showPostInput struct {
|
||||||
type showPostInput struct {
|
|
||||||
ID int `json:"id" path:"id" jsonschema:"the post id"`
|
ID int `json:"id" path:"id" jsonschema:"the post id"`
|
||||||
}
|
}
|
||||||
|
type listPostsInput struct {
|
||||||
func (p Plugin) MCP() pact.MCP {
|
Query string `json:"q,omitempty" query:"q" jsonschema:"a phrase the title or body contains"`
|
||||||
return pact.MCP{Tools: []pact.MCPTool{
|
}
|
||||||
{Name: "create_post", Title: "Create post", Description: "Creates a draft post.",
|
return pact.MCP{
|
||||||
Guard: "backend", Method: "POST", Path: "/_blog/api/v1/posts", Input: createPostInput{},
|
Tools: []pact.MCPTool{
|
||||||
Permissions: []string{"acme.blog.access_posts"}},
|
{
|
||||||
{Name: "show_post", Title: "Show post", Description: "Shows one post.",
|
// Exposed as blog_create_post; the backend guard runs it as
|
||||||
Method: "GET", Path: "/_blog/api/v1/posts/{id}", Input: showPostInput{}},
|
// 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
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -31,14 +31,30 @@ Use cases:
|
|||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
```go
|
```go src=modules/seaglass/example_test.go#ExampleSanitizeReport
|
||||||
clean, report := seaglass.SanitizeReport(`<p onclick="x()">Hi</p><script>alert(1)</script>`)
|
clean, report := seaglass.SanitizeReport(`<p onclick="x()">Hi</p><script>alert(1)</script>`)
|
||||||
// clean == "<p>Hi</p>"
|
fmt.Println(clean)
|
||||||
// report.Elements == []string{"script"}, report.Attributes == []string{"onclick"}
|
fmt.Println(report.Elements, report.Attributes, report.Changed)
|
||||||
|
// Output:
|
||||||
|
// <p>Hi</p>
|
||||||
|
// [script] [onclick] true
|
||||||
|
```
|
||||||
|
|
||||||
if err := seaglass.Check(stored); err != nil {
|
```go src=modules/seaglass/example_test.go#ExampleCheck
|
||||||
|
for _, stored := range []string{
|
||||||
|
`<p class="lead">Hi <a href="tel:+48123">call</a></p>`,
|
||||||
|
`<p><a href="javascript:alert(1)">x</a></p>`,
|
||||||
|
} {
|
||||||
|
if err := seaglass.Check(stored); err != nil {
|
||||||
// stored HTML would change under the policy
|
// 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
|
## API reference
|
||||||
|
|||||||
33
modules/seaglass/example_test.go
Normal file
33
modules/seaglass/example_test.go
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
package seaglass_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/seaglass"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ExampleSanitizeReport() {
|
||||||
|
clean, report := seaglass.SanitizeReport(`<p onclick="x()">Hi</p><script>alert(1)</script>`)
|
||||||
|
fmt.Println(clean)
|
||||||
|
fmt.Println(report.Elements, report.Attributes, report.Changed)
|
||||||
|
// Output:
|
||||||
|
// <p>Hi</p>
|
||||||
|
// [script] [onclick] true
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleCheck() {
|
||||||
|
for _, stored := range []string{
|
||||||
|
`<p class="lead">Hi <a href="tel:+48123">call</a></p>`,
|
||||||
|
`<p><a href="javascript:alert(1)">x</a></p>`,
|
||||||
|
} {
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -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:
|
Serving the script from a Go handler:
|
||||||
|
|
||||||
```go
|
```go src=modules/sunrise/example_test.go#newScript
|
||||||
package acme
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/sunrise"
|
|
||||||
)
|
|
||||||
|
|
||||||
func newScript(w http.ResponseWriter, r *http.Request) {
|
func newScript(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||||
|
|||||||
35
modules/sunrise/example_test.go
Normal file
35
modules/sunrise/example_test.go
Normal file
@@ -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
|
||||||
|
}
|
||||||
@@ -30,21 +30,34 @@ Use cases:
|
|||||||
|
|
||||||
## Usage
|
## 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
|
```go src=modules/sunscreen/example_test.go#startLogging
|
||||||
func main() {
|
// startLogging is the first thing the main function of a program that does
|
||||||
sunscreen.InstallDefault(os.Stderr)
|
// 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:
|
To redact another handler, for example a JSON handler in a custom binary, wrap it:
|
||||||
|
|
||||||
```go
|
```go src=modules/sunscreen/example_test.go#ExampleWrap_json
|
||||||
logger := slog.New(sunscreen.Wrap(slog.NewJSONHandler(os.Stderr, nil)))
|
// 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)
|
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.
|
Redaction is a safety net, not a licence: log ids and outcomes, never request bodies, tokens or arguments that carry them.
|
||||||
|
|||||||
@@ -1,9 +1,14 @@
|
|||||||
package sunscreen_test
|
package sunscreen_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"errors"
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/sunscreen"
|
"git.golem15.com/golem15/summercms/modules/sunscreen"
|
||||||
)
|
)
|
||||||
@@ -28,3 +33,50 @@ func ExampleWrap() {
|
|||||||
// Output:
|
// Output:
|
||||||
// level=INFO msg="vendor call failed" api_key=[REDACTED] request.Authorization=[REDACTED] err="401 for key sk-[REDACTED]"
|
// 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -41,38 +41,48 @@ Use cases:
|
|||||||
|
|
||||||
Record a flow once against the reference backend, then replay it against the port:
|
Record a flow once against the reference backend, then replay it against the port:
|
||||||
|
|
||||||
```go
|
```go src=modules/tide/example_test.go#parity
|
||||||
spec, err := tide.LoadFlow("testdata/parity/posts.spec.yaml")
|
// parity records the flow spec kept in dir against the reference backend
|
||||||
if err != nil {
|
// 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
|
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)
|
|
||||||
}
|
}
|
||||||
|
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:
|
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{
|
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",
|
APIKey: "test-only-key",
|
||||||
Store: store,
|
Store: store,
|
||||||
Step: "delete",
|
Step: "delete",
|
||||||
@@ -81,7 +91,7 @@ golden, err := tide.RecordBroadcasts(ctx, spec, tide.BroadcastConfig{
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,7 +101,7 @@ if err != nil {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
for _, d := range tide.DiffPublications(golden.Publications, norm) {
|
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)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,19 @@
|
|||||||
package tide_test
|
package tide_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/tide"
|
"git.golem15.com/golem15/summercms/modules/tide"
|
||||||
)
|
)
|
||||||
@@ -67,3 +74,181 @@ func ExampleReplayFlow() {
|
|||||||
// ok: false
|
// ok: false
|
||||||
// list-posts $.data[0].title: want "Hello", got "hello"
|
// 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user