Files
summercms/cmd/summer/parity.go
Jakub Zych 9ecbf74a22 feat(11-06): add the tide fake Centrifugo recorder, broadcast goldens and parity:broadcasts
- CentrifugoRecorder records publish/broadcast requests (method, path,
  whether the API key matched, JSON body) and binds loopback only
- BroadcastGolden load/write, NormalizePublications (timestamps, actor,
  captured ids only) and DiffPublications (structural, key order ignored)
- RecordBroadcasts runs a flow or one step against a loopback backend
- summer parity:broadcasts wraps it; README documents format and rules
2026-09-30 13:21:23 +02:00

424 lines
13 KiB
Go

package main
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"git.golem15.com/golem15/summercms/modules/bonfire"
"git.golem15.com/golem15/summercms/modules/tide"
)
func parityProxyCommand() bonfire.Command {
return bonfire.Command{
Name: "parity:proxy",
Description: "Record named HTTP sessions through a loopback reverse proxy",
Flags: []bonfire.Flag{
{Name: "listen", Description: "Loopback bind address", Default: tide.DefaultListen},
{Name: "upstream", Description: "Fixed loopback HTTP origin", Default: tide.DefaultUpstream},
{Name: "session", Description: "Default session name when X-Parity-Session is absent"},
{Name: "rules", Description: "Committed YAML capture rules"},
{Name: "vars", Description: "Private mode-0600 variable store outside fixtures"},
{Name: "fixtures", Description: "Directory for nuxt/ and mcp/ session flows"},
{Name: "update", Description: "Overwrite existing session fixtures (true/false)"},
},
Run: runParityProxy,
}
}
func parityRecordCommand() bonfire.Command {
return bonfire.Command{
Name: "parity:record",
Description: "Record HTTP responses for a one-flow YAML spec",
Flags: []bonfire.Flag{
{Name: "spec", Description: "YAML request spec path"},
{Name: "target", Description: "Base URL of the HTTP backend"},
{Name: "output", Description: "Destination fixture path"},
{Name: "rules", Description: "Committed YAML capture rules"},
{Name: "vars", Description: "Private mode-0600 variable store outside fixtures"},
{Name: "manifest", Description: "Route manifest path"},
{Name: "fixtures", Description: "Fixture directory for manifest recording"},
{Name: "update", Description: "Overwrite existing fixtures (true/false)"},
{Name: "next-batch", Description: "Max unrecorded routes to record (max 15)"},
{Name: "resume", Description: "Skip valid existing fixtures (true/false)"},
{Name: "allow-incomplete", Description: "Permit unfinished cases (true/false)"},
{Name: "require-recorded", Description: "Require a fixture for every case (true/false)"},
},
Run: runParityRecord,
}
}
func parityReplayCommand() bonfire.Command {
return bonfire.Command{
Name: "parity:replay",
Description: "Replay recorded fixtures against an HTTP backend",
Flags: []bonfire.Flag{
{Name: "fixtures", Description: "Recorded YAML fixture path or directory"},
{Name: "target", Description: "Base URL of the HTTP backend"},
{Name: "vars", Description: "Private mode-0600 variable store"},
{Name: "manifest", Description: "Route manifest path"},
{Name: "self-check", Description: "Fail on any recorded mismatch (true/false)"},
{Name: "require-recorded", Description: "Fail unrecorded required cases (true/false)"},
},
Run: runParityReplay,
}
}
func parityBroadcastsCommand() bonfire.Command {
return bonfire.Command{
Name: "parity:broadcasts",
Description: "Record the Centrifugo publications a reference backend sends during a flow into a golden",
Flags: []bonfire.Flag{
{Name: "flow", Description: "YAML flow spec to run against the target"},
{Name: "target", Description: "Loopback base URL of the reference backend"},
{Name: "vars", Description: "Private mode-0600 variable store outside fixtures"},
{Name: "listen", Description: "Loopback address of the fake Centrifugo recorder", Default: tide.DefaultCentrifugoListen},
{Name: "out", Description: "Destination golden path"},
{Name: "name", Description: "Golden name (default: the step, else the flow name)"},
{Name: "step", Description: "Record only this step's publications; earlier steps run as setup"},
{Name: "ids", Description: "Comma-separated id:* variables to replace with placeholders"},
{Name: "rules", Description: "Committed YAML capture rules"},
{Name: "api-key", Description: "Centrifugo API key the backend sends (default: $PARITY_CENTRIFUGO_API_KEY)"},
{Name: "settle", Description: "Wait for late publications after each step (Go duration)", Default: tide.DefaultBroadcastSettle.String()},
{Name: "pending", Description: "Mark the golden recorded but not yet asserted, with this reason"},
},
Run: runParityBroadcasts,
}
}
func runParityBroadcasts(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
flowPath, err := requireFlag(in, "flow", "parity:broadcasts")
if err != nil {
return err
}
target, err := requireFlag(in, "target", "parity:broadcasts")
if err != nil {
return err
}
outPath, err := requireFlag(in, "out", "parity:broadcasts")
if err != nil {
return err
}
varsPath, err := requireFlag(in, "vars", "parity:broadcasts")
if err != nil {
return err
}
if err := varsOutsideDir(varsPath, filepath.Dir(outPath)); err != nil {
return err
}
apiKey := flagValue(in, "api-key")
if apiKey == "" {
apiKey = strings.TrimSpace(os.Getenv("PARITY_CENTRIFUGO_API_KEY"))
}
if apiKey == "" {
return fmt.Errorf("parity:broadcasts requires --api-key or PARITY_CENTRIFUGO_API_KEY")
}
spec, err := tide.LoadFlow(flowPath)
if err != nil {
return err
}
cfg := tide.BroadcastConfig{
Target: target,
Listen: flagValue(in, "listen"),
APIKey: apiKey,
Step: flagValue(in, "step"),
Name: flagValue(in, "name"),
}
if s := flagValue(in, "settle"); s != "" {
d, err := time.ParseDuration(s)
if err != nil {
return fmt.Errorf("parity:broadcasts --settle: %w", err)
}
cfg.Settle = d
}
for _, id := range strings.Split(flagValue(in, "ids"), ",") {
if id = strings.TrimSpace(id); id != "" {
cfg.IDs = append(cfg.IDs, id)
}
}
rc := tide.RecordConfig{}
if err := attachRulesAndVars(in, &rc); err != nil {
return err
}
cfg.Rules, cfg.Store = rc.Rules, rc.Store
golden, err := tide.RecordBroadcasts(ctx, spec, cfg)
if err != nil {
return err
}
golden.Pending = flagValue(in, "pending")
if err := tide.WriteBroadcastGolden(outPath, golden); err != nil {
return err
}
out.Success(fmt.Sprintf("recorded %d publications into %s", len(golden.Publications), outPath))
return nil
}
// varsOutsideDir refuses a vars store inside the directory a golden is
// written to, so captured secrets never sit next to committed files.
func varsOutsideDir(varsPath, dir string) error {
absVars, err := filepath.Abs(varsPath)
if err != nil {
return err
}
absDir, err := filepath.Abs(dir)
if err != nil {
return err
}
if eval, err := filepath.EvalSymlinks(absDir); err == nil {
absDir = eval
}
if eval, err := filepath.EvalSymlinks(filepath.Dir(absVars)); err == nil {
absVars = filepath.Join(eval, filepath.Base(absVars))
}
if absVars == absDir || strings.HasPrefix(absVars, absDir+string(os.PathSeparator)) {
return fmt.Errorf("parity:broadcasts: vars file %q must be outside %q", varsPath, dir)
}
return nil
}
func runParityProxy(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
rulesPath, err := requireFlag(in, "rules", "parity:proxy")
if err != nil {
return err
}
fixtures, err := requireFlag(in, "fixtures", "parity:proxy")
if err != nil {
return err
}
rules, err := tide.LoadRules(rulesPath)
if err != nil {
return err
}
listen, _ := in.Flag("listen")
upstream, _ := in.Flag("upstream")
session, _ := in.Flag("session")
varsPath, _ := in.Flag("vars")
proxy, err := tide.NewProxy(tide.ProxyConfig{
Listen: listen,
Upstream: upstream,
Session: session,
Rules: rules,
VarsPath: varsPath,
Fixtures: fixtures,
Update: flagBool(in, "update"),
})
if err != nil {
return err
}
out.Info(fmt.Sprintf("proxy listening on %s → %s", listen, upstream))
return proxy.ListenAndServe(ctx)
}
func runParityRecord(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
if man, ok := in.Flag("manifest"); ok && strings.TrimSpace(man) != "" {
return runParityRecordManifest(ctx, in, out, strings.TrimSpace(man))
}
specPath, err := requireFlag(in, "spec", "parity:record")
if err != nil {
return err
}
target, err := requireFlag(in, "target", "parity:record")
if err != nil {
return err
}
output, err := requireFlag(in, "output", "parity:record")
if err != nil {
return err
}
spec, err := tide.LoadFlow(specPath)
if err != nil {
return err
}
cfg := tide.RecordConfig{Target: target}
if err := attachRulesAndVars(in, &cfg); err != nil {
return err
}
flow, err := tide.RecordFlow(ctx, spec, cfg)
if err != nil {
return err
}
if err := tide.SaveFlow(output, flow); err != nil {
return err
}
out.Success(fmt.Sprintf("recorded %s", output))
return nil
}
func runParityRecordManifest(ctx context.Context, in bonfire.Input, out bonfire.Output, manPath string) error {
target, err := requireFlag(in, "target", "parity:record")
if err != nil {
return err
}
fixtures, err := requireFlag(in, "fixtures", "parity:record")
if err != nil {
return err
}
m, err := tide.LoadManifest(manPath)
if err != nil {
return err
}
mode := tide.ModeAllowIncomplete
if flagBool(in, "require-recorded") {
mode = tide.ModeRequireRecorded
}
if err := tide.ValidateManifest(m, fixtures, mode); err != nil && mode == tide.ModeRequireRecorded {
return err
}
if err := tide.ValidateManifest(m, fixtures, tide.ModeAllowIncomplete); err != nil {
return err
}
batch, err := tide.ParseNextBatch(flagValue(in, "next-batch"))
if err != nil {
return err
}
cfg := tide.ManifestConfig{
Target: target,
Fixtures: fixtures,
Update: flagBool(in, "update"),
Resume: flagBool(in, "resume"),
NextBatch: batch,
Mode: mode,
}
if err := attachManifestStore(in, &cfg); err != nil {
return err
}
cov, err := tide.RecordManifest(ctx, m, cfg)
if err != nil {
return err
}
out.Table(tide.CoverageHeaders(), cov.CoverageRows())
out.Success(cov.SummaryLine())
out.Info(cov.ResumeLine())
return nil
}
func runParityReplay(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
target, err := requireFlag(in, "target", "parity:replay")
if err != nil {
return err
}
if man, ok := in.Flag("manifest"); ok && strings.TrimSpace(man) != "" {
return runParityReplayManifest(ctx, in, out, strings.TrimSpace(man), target)
}
path, err := requireFlag(in, "fixtures", "parity:replay")
if err != nil {
return err
}
flow, err := tide.LoadFlow(path)
if err != nil {
return err
}
cfg := tide.ReplayConfig{Target: target, BaseDir: filepath.Dir(path)}
if varsPath, ok := in.Flag("vars"); ok && strings.TrimSpace(varsPath) != "" {
store, err := tide.OpenStore(varsPath)
if err != nil {
return err
}
cfg.Store = store
}
result, err := tide.ReplayFlow(ctx, flow, cfg)
if err != nil {
return err
}
if result.OK {
out.Success("replay matched")
}
return nil
}
func runParityReplayManifest(ctx context.Context, in bonfire.Input, out bonfire.Output, manPath, target string) error {
fixtures, err := requireFlag(in, "fixtures", "parity:replay")
if err != nil {
return err
}
m, err := tide.LoadManifest(manPath)
if err != nil {
return err
}
cfg := tide.ManifestConfig{
Target: target,
Fixtures: fixtures,
SelfCheck: flagBool(in, "self-check"),
Mode: tide.ModeAllowIncomplete,
}
if flagBool(in, "require-recorded") {
cfg.Mode = tide.ModeRequireRecorded
}
if err := attachManifestStore(in, &cfg); err != nil {
return err
}
cov, err := tide.ReplayManifest(ctx, m, cfg)
for _, d := range cov.Diffs {
out.Error(d)
}
out.Table(tide.CoverageHeaders(), cov.CoverageRows())
out.Info(cov.SummaryLine())
return err
}
func attachRulesAndVars(in bonfire.Input, cfg *tide.RecordConfig) error {
if rulesPath, ok := in.Flag("rules"); ok && strings.TrimSpace(rulesPath) != "" {
rules, err := tide.LoadRules(rulesPath)
if err != nil {
return err
}
cfg.Rules = rules
}
if varsPath, ok := in.Flag("vars"); ok && strings.TrimSpace(varsPath) != "" {
store, err := tide.OpenStore(varsPath)
if err != nil {
return err
}
cfg.Store = store
}
return nil
}
func attachManifestStore(in bonfire.Input, cfg *tide.ManifestConfig) error {
if rulesPath, ok := in.Flag("rules"); ok && strings.TrimSpace(rulesPath) != "" {
rules, err := tide.LoadRules(rulesPath)
if err != nil {
return err
}
cfg.Rules = rules
}
if varsPath, ok := in.Flag("vars"); ok && strings.TrimSpace(varsPath) != "" {
store, err := tide.OpenStore(varsPath)
if err != nil {
return err
}
cfg.Store = store
}
return nil
}
func flagBool(in bonfire.Input, name string) bool {
v, ok := in.Flag(name)
if !ok {
return false
}
switch strings.ToLower(strings.TrimSpace(v)) {
case "", "true", "1", "yes":
return true
default:
return false
}
}
func flagValue(in bonfire.Input, name string) string {
v, _ := in.Flag(name)
return strings.TrimSpace(v)
}
func requireFlag(in bonfire.Input, name, cmd string) (string, error) {
v, ok := in.Flag(name)
v = strings.TrimSpace(v)
if !ok || v == "" {
return "", fmt.Errorf("%s requires --%s", cmd, name)
}
return v, nil
}