Skip to content

armgit / khaos

Public Imported from GitHub
0

Kafka data generator and load testing tool - generate fake messages, simulate producers and consumers, test broker failures, and run chaos engineering scenarios

refactor: table-driven error classification, split validate.go, name tui budgets, drop dead counters and symbols

aleksandarskrbicc37cd0aa8eea
diff --git a/RUNBOOK.md b/RUNBOOK.md
index f345aa2..a99d863 100644
--- a/RUNBOOK.md
+++ b/RUNBOOK.md
@@ -26,8 +26,9 @@ CI job.
### Build
+From the repository root:
+
```bash
-cd ~/GoProjects/khaos
go build -o khaos ./cmd/khaos
./khaos --version
```
diff --git a/cmd/khaos/summary.go b/cmd/khaos/summary.go
index 873506a..ce4ba8c 100644
--- a/cmd/khaos/summary.go
+++ b/cmd/khaos/summary.go
@@ -24,8 +24,13 @@ func summary(w io.Writer, s engine.Snapshot, hadTUI bool) {
styHeader.Render(s.Scenario),
styDim.Render(" · elapsed "+s.Elapsed.Round(time.Second).String()))
+ // The TOTAL row is a TopicStat too, so one row builder serves both.
+ total := engine.TopicStat{Topic: "TOTAL", Produced: s.TotalProduced, Consumed: s.TotalConsumed}
+ total.Lag = total.Produced - total.Consumed
failures := false
for _, t := range s.Topics {
+ total.Failed += t.Failed
+ total.DLQ += t.DLQ
if t.Failed > 0 || t.DLQ > 0 {
failures = true
}
@@ -36,32 +41,9 @@ func summary(w io.Writer, s engine.Snapshot, hadTUI bool) {
}
rows := make([][]string, 0, len(s.Topics)+1)
for _, t := range s.Topics {
- row := []string{
- styScenario.Render(t.Topic),
- styOK.Render(thousands(t.Produced)),
- styWarn.Render(thousands(t.Consumed)),
- summaryLag(t.Lag),
- }
- if failures {
- row = append(row, summaryBlankZero(t.Failed), summaryBlankZero(t.DLQ))
- }
- rows = append(rows, row)
- }
- total := []string{
- styHeader.Render("TOTAL"),
- styOK.Render(thousands(s.TotalProduced)),
- styWarn.Render(thousands(s.TotalConsumed)),
- summaryLag(s.TotalProduced - s.TotalConsumed),
- }
- if failures {
- var tf, td int64
- for _, t := range s.Topics {
- tf += t.Failed
- td += t.DLQ
- }
- total = append(total, summaryBlankZero(tf), summaryBlankZero(td))
+ rows = append(rows, summaryRow(t, styScenario, failures))
}
- rows = append(rows, total)
+ rows = append(rows, summaryRow(total, styHeader, failures))
fmt.Fprintln(w, summaryTable(headers, rows))
if len(s.Flows) > 0 {
@@ -89,6 +71,21 @@ func summary(w io.Writer, s engine.Snapshot, hadTUI bool) {
}
}
+// summaryRow renders one line of the topic table; the FAILED and DLQ cells are only
+// present when the table has those columns.
+func summaryRow(t engine.TopicStat, nameStyle lipgloss.Style, failures bool) []string {
+ row := []string{
+ nameStyle.Render(t.Topic),
+ styOK.Render(thousands(t.Produced)),
+ styWarn.Render(thousands(t.Consumed)),
+ summaryLag(t.Lag),
+ }
+ if failures {
+ row = append(row, summaryBlankZero(t.Failed), summaryBlankZero(t.DLQ))
+ }
+ return row
+}
+
// summaryTable is the shared khaos table look, with numeric columns right-aligned.
func summaryTable(headers []string, rows [][]string) string {
return table.New().
diff --git a/internal/codec/avro.go b/internal/codec/avro.go
index 9af8055..9185d69 100644
--- a/internal/codec/avro.go
+++ b/internal/codec/avro.go
@@ -250,22 +250,19 @@ func avroDecodedValue(s avroSchemaNode, v any) any {
if v == nil {
return nil
}
- wrapped, ok := v.(map[string]any)
- if !ok || len(wrapped) != 1 {
+ wrapped, _ := v.(map[string]any)
+ branchName, branchVal, ok := onlyPair(wrapped)
+ if !ok {
return v
}
- // wrapped has exactly one entry, checked above; ranging is how to reach
- // it. Every path inside returns, so this loop never takes a second turn.
- for branchName, branchVal := range wrapped {
- for _, branch := range s.union {
- if branchMatchesName(*branch, branchName) {
- return avroDecodedValue(*branch, branchVal)
- }
+ for _, branch := range s.union {
+ if branchMatchesName(*branch, branchName) {
+ return avroDecodedValue(*branch, branchVal)
}
- // Unknown branch name (should not happen against our own parsed
- // schema): pass the raw value through rather than dropping it.
- return branchVal
}
+ // Unknown branch name (should not happen against our own parsed
+ // schema): pass the raw value through rather than dropping it.
+ return branchVal
}
switch s.typeName {
@@ -336,6 +333,17 @@ func branchMatchesName(branch avroSchemaNode, branchName string) bool {
return branch.typeName == branchName
}
+// onlyPair returns the single entry of a one-entry map; ok is false for a map
+// of any other size (nil included).
+func onlyPair[K comparable, V any](m map[K]V) (k K, v V, ok bool) {
+ if len(m) != 1 {
+ return k, v, false
+ }
+ for k, v = range m {
+ }
+ return k, v, true
+}
+
func sortedKeys(m map[string]any) []string {
keys := make([]string, 0, len(m))
for k := range m {
@@ -474,9 +482,7 @@ func buildAvroSchemaNode(raw any, enclosingNS string, ctx *avroSchemaBuildCtx) (
switch typeName {
case "record", "error":
node.typeName = "record"
- name, _ := t["name"].(string)
- node.fullName = qualifyAvroName(name, ns)
- registerAvroName(ctx, node, name, node.fullName)
+ declareNamedType(t, ns, node, ctx)
rawFields, _ := t["fields"].([]any)
for _, rf := range rawFields {
fm, ok := rf.(map[string]any)
@@ -490,14 +496,8 @@ func buildAvroSchemaNode(raw any, enclosingNS string, ctx *avroSchemaBuildCtx) (
}
node.fields = append(node.fields, avroFieldNode{name: fname, typ: ft})
}
- case "enum":
- name, _ := t["name"].(string)
- node.fullName = qualifyAvroName(name, ns)
- registerAvroName(ctx, node, name, node.fullName)
- case "fixed":
- name, _ := t["name"].(string)
- node.fullName = qualifyAvroName(name, ns)
- registerAvroName(ctx, node, name, node.fullName)
+ case "enum", "fixed":
+ declareNamedType(t, ns, node, ctx)
case "array":
items, err := buildAvroSchemaNode(t["items"], ns, ctx)
if err != nil {
@@ -511,18 +511,9 @@ func buildAvroSchemaNode(raw any, enclosingNS string, ctx *avroSchemaBuildCtx) (
}
node.values = values
default:
- // A primitive spelled out as {"type":"string",...} (e.g. carrying a
- // logicalType) -- typeName is already set correctly above, unless
- // goavro compiles this particular (type, logicalType) pair under a
- // compound key (see avroCompoundLogicalTypeNames), in which case the
- // node's typeName must match that compound key or union branch
- // wrapping (encode) and matching (decode) picks the wrong name.
- if lt, ok := t["logicalType"].(string); ok && lt != "" {
- compound := typeName + "." + lt
- if avroCompoundLogicalTypeNames[compound] {
- node.typeName = compound
- }
- }
+ // A primitive spelled out as {"type":"string",...}, possibly
+ // carrying a logicalType.
+ node.typeName = avroLogicalTypeKey(typeName, t)
}
return node, nil
@@ -531,6 +522,30 @@ func buildAvroSchemaNode(raw any, enclosingNS string, ctx *avroSchemaBuildCtx) (
}
}
+// declareNamedType is the prologue shared by every named type (record, enum,
+// fixed): it qualifies the declaration's name with its namespace and registers
+// node under it so later references resolve.
+func declareNamedType(t map[string]any, ns string, node *avroSchemaNode, ctx *avroSchemaBuildCtx) {
+ name, _ := t["name"].(string)
+ node.fullName = qualifyAvroName(name, ns)
+ registerAvroName(ctx, node, name, node.fullName)
+}
+
+// avroLogicalTypeKey returns the type name a primitive node must carry: the
+// bare typeName, unless goavro compiles this particular (type, logicalType)
+// pair under a compound key (see avroCompoundLogicalTypeNames), in which case
+// the node's typeName must match that compound key or union branch wrapping
+// (encode) and matching (decode) picks the wrong name.
+func avroLogicalTypeKey(typeName string, t map[string]any) string {
+ if lt, ok := t["logicalType"].(string); ok && lt != "" {
+ compound := typeName + "." + lt
+ if avroCompoundLogicalTypeNames[compound] {
+ return compound
+ }
+ }
+ return typeName
+}
+
// registerAvroName records node under both its bare and namespace-qualified
// names, so a later reference resolves whichever form it uses.
func registerAvroName(ctx *avroSchemaBuildCtx, node *avroSchemaNode, bareName, fullName string) {
diff --git a/internal/codec/convert_test.go b/internal/codec/convert_test.go
index 86da1b7..0f3a370 100644
--- a/internal/codec/convert_test.go
+++ b/internal/codec/convert_test.go
@@ -15,7 +15,7 @@ func TestAvroFieldsFromSchema(t *testing.T) {
want []scenario.Field
}{
{
- name: "primitives map back through AVRO_TYPE_MAP",
+ name: "primitives map back through avroFieldTypes",
schema: `{"type":"record","name":"R","fields":[{"name":"a","type":"string"},{"name":"b","type":"long"},{"name":"c","type":"int"},{"name":"d","type":"double"},{"name":"e","type":"float"},{"name":"f","type":"boolean"},{"name":"g","type":"bytes"}]}`,
want: []scenario.Field{
fld("a", scenario.FieldString),
diff --git a/internal/codec/registry.go b/internal/codec/registry.go
index 43cb748..2477984 100644
--- a/internal/codec/registry.go
+++ b/internal/codec/registry.go
@@ -227,34 +227,57 @@ func (c RegistryConfig) authError(what string, err error) error {
c.URL, what, re.StatusCode, http.StatusText(re.StatusCode), c.authHint(re.StatusCode), err)
}
-// authHint is the "probably this flag" half of authError.
-func (c RegistryConfig) authHint(status int) string {
- const confluentNote = "on Confluent Cloud these are the Schema Registry API key and secret, " +
- "which are NOT the Kafka cluster API key and secret"
+// registryCredential is which kind of credential a RegistryConfig carries, the first half of
+// the key into registryAuthHints.
+type registryCredential int
+
+const (
+ registryCredentialNone registryCredential = iota
+ registryCredentialBearer
+ registryCredentialBasic
+)
+
+// registryAuthKey selects one registryAuthHints entry: what was sent, and whether the
+// registry rejected it outright (401) or accepted it but refused the request (403).
+type registryAuthKey struct {
+ credential registryCredential
+ status int
+}
+
+const confluentRegistryNote = "on Confluent Cloud these are the Schema Registry API key and secret, " +
+ "which are NOT the Kafka cluster API key and secret"
+
+// registryAuthHints holds the "probably this flag" message for every credential kind and
+// rejection status authError can see.
+var registryAuthHints = map[registryAuthKey]string{
+ {registryCredentialBearer, http.StatusForbidden}: "the token in --schema-registry-token was " +
+ "accepted but is not allowed to do this; check its role bindings, and that it was " +
+ "issued for THIS registry",
+ {registryCredentialBearer, http.StatusUnauthorized}: "check --schema-registry-token: it may " +
+ "have expired or belong to another registry",
+ {registryCredentialBasic, http.StatusForbidden}: "the credentials were accepted but are not " +
+ "allowed to do this; check the subject-level ACLs, and that --schema-registry-username " +
+ "is a key for THIS registry (" + confluentRegistryNote + ")",
+ {registryCredentialBasic, http.StatusUnauthorized}: "check --schema-registry-username and " +
+ "--schema-registry-password: " + confluentRegistryNote,
+ {registryCredentialNone, http.StatusForbidden}: "no credentials were sent; pass " +
+ "--schema-registry-username and --schema-registry-password, or --schema-registry-token",
+ {registryCredentialNone, http.StatusUnauthorized}: "this registry requires authentication " +
+ "but no credentials were given; pass --schema-registry-username and " +
+ "--schema-registry-password (" + confluentRegistryNote + "), or --schema-registry-token",
+}
+// authHint is the "probably this flag" half of authError: it classifies the credential kind
+// the same way clientOpts does and looks the message up in registryAuthHints.
+func (c RegistryConfig) authHint(status int) string {
+ credential := registryCredentialNone
switch {
case c.BearerToken != "":
- if status == http.StatusForbidden {
- return "the token in --schema-registry-token was accepted but is not allowed to do " +
- "this; check its role bindings, and that it was issued for THIS registry"
- }
- return "check --schema-registry-token: it may have expired or belong to another registry"
+ credential = registryCredentialBearer
case c.usesBasicAuth():
- if status == http.StatusForbidden {
- return "the credentials were accepted but are not allowed to do this; check the " +
- "subject-level ACLs, and that --schema-registry-username is a key for THIS " +
- "registry (" + confluentNote + ")"
- }
- return "check --schema-registry-username and --schema-registry-password: " + confluentNote
- default:
- if status == http.StatusForbidden {
- return "no credentials were sent; pass --schema-registry-username and " +
- "--schema-registry-password, or --schema-registry-token"
- }
- return "this registry requires authentication but no credentials were given; pass " +
- "--schema-registry-username and --schema-registry-password (" + confluentNote +
- "), or --schema-registry-token"
+ credential = registryCredentialBasic
}
+ return registryAuthHints[registryAuthKey{credential, status}]
}
// NewRegistry builds a registry client from a bare URL, with no authentication.
diff --git a/internal/engine/consumer.go b/internal/engine/consumer.go
index 3a11834..a113e80 100644
--- a/internal/engine/consumer.go
+++ b/internal/engine/consumer.go
@@ -210,43 +210,62 @@ func (c *Consumer) handle(ctx context.Context, rec *kgo.Record) {
return
}
- // Failure simulation: roll for failure, dispatch on on_failure, and only commit on
- // success. The commit is then subject to an independent commit_failure_rate whose
- // "failure" is declining to commit rather than an error from the broker.
- attempts := 0
- for {
- if c.rnd.Float64() >= c.Conf.FailureRate {
- break // processed successfully
+ // Failure simulation: roll, dispatch on on_failure, and only commit on success. The
+ // commit is then subject to an independent commit_failure_rate whose "failure" is
+ // declining to commit rather than an error from the broker.
+ switch c.simulateFailure() {
+ case outcomeProcessed:
+ c.stats.consumed.Add(1)
+ c.topicC.consumed.Add(1)
+ if c.promConsumed != nil {
+ c.promConsumed.Inc()
}
+ c.maybeCommit(ctx, rec)
+ case outcomeDLQ:
+ c.sendDLQ(ctx, rec)
+ case outcomeDropped:
+ }
+}
+
+// failureOutcome is what the failure simulation decided to do with one record.
+type failureOutcome int
+
+const (
+ // outcomeProcessed: the record counts as consumed and is committed.
+ outcomeProcessed failureOutcome = iota
+ // outcomeDropped: the record is skipped -- on_failure "skip", or "retry" with the
+ // retry budget exhausted -- and nothing further is counted.
+ outcomeDropped
+ // outcomeDLQ: the record goes to the dead-letter topic.
+ outcomeDLQ
+)
+// simulateFailure rolls against failure_rate and resolves on_failure to an outcome.
+//
+// Failed counts every failed attempt, so with on_failure "retry" one record can add up to
+// max_retries to Failed while Retries counts the re-attempts actually made (one fewer
+// than the failures, since the last failure is not followed by a retry).
+func (c *Consumer) simulateFailure() failureOutcome {
+ for attempts := 0; ; attempts++ {
+ if c.rnd.Float64() >= c.Conf.FailureRate {
+ return outcomeProcessed
+ }
c.stats.failed.Add(1)
c.topicC.failed.Add(1)
switch c.Conf.OnFailure {
- case "skip":
- return
case "dlq":
- c.sendDLQ(ctx, rec)
- return
+ return outcomeDLQ
case "retry":
- attempts++
- if attempts >= c.Conf.MaxRetries {
- return
+ if attempts+1 >= c.Conf.MaxRetries {
+ return outcomeDropped
}
c.stats.retries.Add(1)
c.topicC.retries.Add(1)
- continue
- default:
- return
+ default: // "skip", which validation guarantees is the only other value
+ return outcomeDropped
}
}
-
- c.stats.consumed.Add(1)
- c.topicC.consumed.Add(1)
- if c.promConsumed != nil {
- c.promConsumed.Inc()
- }
- c.maybeCommit(ctx, rec)
}
// maybeCommit commits the record unless the simulated commit failure fires.
diff --git a/internal/engine/producer.go b/internal/engine/producer.go
index f4b943d..afb8219 100644
--- a/internal/engine/producer.go
+++ b/internal/engine/producer.go
@@ -36,10 +36,8 @@ type Producer struct {
dupRate float64
rnd *rand.Rand
- // stats is this producer's own tally, topicC the shared per-topic one. Only topicC
- // reaches Snapshot -- nothing reads a single producer's counters today, and no
- // per-producer row is rendered anywhere.
- stats *counters
+ // topicC is the per-topic counter set shared with every producer on this topic; it
+ // is what Snapshot and the Prometheus series read.
topicC *counters
events *eventRing
@@ -79,7 +77,6 @@ func newProducer(o producerOpts) *Producer {
limiter: newLimiter(o.rate),
dupRate: o.dupRate,
rnd: o.rnd,
- stats: &counters{},
topicC: o.topicC,
events: o.events,
}
@@ -131,7 +128,6 @@ func (p *Producer) Run(ctx context.Context) error {
value, err := p.nextValue()
if err != nil {
- p.stats.produceErr.Add(1)
p.topicC.produceErr.Add(1)
if p.promProduceErr != nil {
p.promProduceErr.Inc()
@@ -152,7 +148,6 @@ func (p *Producer) Run(ctx context.Context) error {
return nil
}
p.produce(ctx, key, value)
- p.stats.duplicate.Add(1)
p.topicC.duplicate.Add(1)
}
}
@@ -179,15 +174,12 @@ func (p *Producer) produce(ctx context.Context, key, value []byte) {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return
}
- p.stats.produceErr.Add(1)
p.topicC.produceErr.Add(1)
if p.promProduceErr != nil {
p.promProduceErr.Inc()
}
return
}
- p.stats.sent.Add(1)
- p.stats.bytes.Add(size)
p.topicC.sent.Add(1)
p.topicC.bytes.Add(size)
if p.promGenerated != nil {
diff --git a/internal/generate/docgen.go b/internal/generate/docgen.go
index eef71b1..fc8e57c 100644
--- a/internal/generate/docgen.go
+++ b/internal/generate/docgen.go
@@ -56,15 +56,14 @@ func newDocGen(fields []scenario.Field, r *rand.Rand, o options) (*DocGen, error
// cardinality cursor.
func (g *DocGen) Next() *Doc {
d := NewDoc(len(g.names))
- for i, name := range g.names {
- d.Set(name, g.gens[i]())
- }
+ g.fill(d)
return d
}
-// Fields returns the field names this generator emits, in declaration order.
-func (g *DocGen) Fields() []string {
- out := make([]string, len(g.names))
- copy(out, g.names)
- return out
+// fill generates one document's fields into d, after whatever keys d already
+// holds. A field named like an existing key overwrites its value in place.
+func (g *DocGen) fill(d *Doc) {
+ for i, name := range g.names {
+ d.Set(name, g.gens[i]())
+ }
}
diff --git a/internal/generate/field.go b/internal/generate/field.go
index 2cc305d..6a3d091 100644
--- a/internal/generate/field.go
+++ b/internal/generate/field.go
@@ -25,11 +25,6 @@ const (
defaultFloatMax = 1000.0
)
-// maxCardinalityAttempts is unreferenced: nothing in the package reads it. The live bound
-// on the distinct-value fill loop is whatever the caller passes to BoundFillAttempts -- the
-// engine passes 4096 -- and with no option the loop in withCardinality is unbounded.
-const maxCardinalityAttempts = 1000
-
// lowercaseAlphabet is the character set generated string fields draw from.
const lowercaseAlphabet = "abcdefghijklmnopqrstuvwxyz"
@@ -126,14 +121,11 @@ func newFieldGen(f scenario.Field, r *rand.Rand, o options) (func() any, error)
case scenario.FieldFloat:
return newFloatGen(f, r, o)
case scenario.FieldBoolean:
- return func() any { return r.IntN(2) == 1 }, nil
+ return newBoolGen(f, r, o)
case scenario.FieldUUID:
- return func() any { return uuid4(r) }, nil
+ return newUUIDGen(f, r, o)
case scenario.FieldTimestamp:
- // Emits epoch milliseconds as an int, despite the README documenting
- // ISO-8601 for this type -- the schema contract is whatever this
- // function returns.
- return func() any { return time.Now().UnixMilli() }, nil
+ return newTimestampGen(f, r, o)
case scenario.FieldEnum:
return newEnumGen(f, r, o)
case scenario.FieldObject:
@@ -223,6 +215,24 @@ func newFloatGen(f scenario.Field, r *rand.Rand, o options) (func() any, error)
}, nil
}
+// newBoolGen builds the generator for a `type: boolean` field: a fair coin.
+func newBoolGen(f scenario.Field, r *rand.Rand, o options) (func() any, error) {
+ return func() any { return r.IntN(2) == 1 }, nil
+}
+
+// newUUIDGen builds the generator for a `type: uuid` field: a fresh version-4
+// UUID per call, drawn from r so seeded runs are reproducible.
+func newUUIDGen(f scenario.Field, r *rand.Rand, o options) (func() any, error) {
+ return func() any { return uuid4(r) }, nil
+}
+
+// newTimestampGen builds the generator for a `type: timestamp` field. It emits
+// epoch milliseconds as an int, despite the README documenting ISO-8601 for
+// this type -- the schema contract is whatever this function returns.
+func newTimestampGen(f scenario.Field, r *rand.Rand, o options) (func() any, error) {
+ return func() any { return time.Now().UnixMilli() }, nil
+}
+
// newEnumGen builds the generator for a `type: enum` field. Duplicate entries
// are the documented way to weight an enum, so the list is used as-is.
func newEnumGen(f scenario.Field, r *rand.Rand, o options) (func() any, error) {
@@ -304,21 +314,12 @@ func withCardinality(f scenario.Field, draw func() any, o options) (func() any,
cache := make([]any, 0, prealloc)
seen := make(map[any]struct{}, prealloc)
for len(cache) < card {
- attempts := 0
- for {
- v := draw()
- if _, dup := seen[v]; !dup {
- seen[v] = struct{}{}
- cache = append(cache, v)
- break
- }
- attempts++
- if o.maxFillAttempts > 0 && attempts >= o.maxFillAttempts {
- return nil, fmt.Errorf(
- "field %q: cannot reach cardinality %d: no new distinct value after %d attempts (had %d); the value space is too small",
- f.Name, card, o.maxFillAttempts, len(cache))
- }
+ v, err := drawDistinct(draw, seen, o.maxFillAttempts)
+ if err != nil {
+ return nil, fmt.Errorf("field %q: cannot reach cardinality %d: %w (had %d); the value space is too small",
+ f.Name, card, err, len(cache))
}
+ cache = append(cache, v)
}
idx := 0
@@ -329,6 +330,24 @@ func withCardinality(f scenario.Field, draw func() any, o options) (func() any,
}, nil
}
+// drawDistinct draws until it gets a value not yet in seen, records it there
+// and returns it. maxAttempts bounds the consecutive rejected draws; zero
+// means unbounded, which hangs if the value space is exhausted.
+func drawDistinct(draw func() any, seen map[any]struct{}, maxAttempts int) (any, error) {
+ attempts := 0
+ for {
+ v := draw()
+ if _, dup := seen[v]; !dup {
+ seen[v] = struct{}{}
+ return v, nil
+ }
+ attempts++
+ if maxAttempts > 0 && attempts >= maxAttempts {
+ return nil, fmt.Errorf("no new distinct value after %d attempts", maxAttempts)
+ }
+ }
+}
+
func cardinalityOf(f scenario.Field) int {
if f.Cardinality == nil {
return 0
diff --git a/internal/generate/flow.go b/internal/generate/flow.go
index 4976ff9..5b67b65 100644
--- a/internal/generate/flow.go
+++ b/internal/generate/flow.go
@@ -108,16 +108,12 @@ func (g *FlowGen) Instance() ([]FlowMessage, error) {
var correlationID string
for i, step := range g.steps {
- doc := g.gens[i].Next()
-
- // Rebuild with the injected keys leading, before the step's fields.
- body := NewDoc(doc.Len() + 2)
+ // The injected keys go in first so they lead the document; the step's
+ // fields are generated straight in after them.
+ body := NewDoc(len(g.gens[i].names) + 2)
body.Set(correlationIDKey, "")
body.Set(eventTypeKey, step.EventType)
- for _, name := range doc.Keys() {
- v, _ := doc.Get(name)
- body.Set(name, v)
- }
+ g.gens[i].fill(body)
if i == 0 {
correlationID = g.correlationID(body)
@@ -146,14 +142,6 @@ func (g *FlowGen) Instance() ([]FlowMessage, error) {
return msgs, nil
}
-// Steps returns the flow's steps.
-//
-// Unlike Doc.Keys and DocGen.Fields this is not a copy: it is the same slice
-// the scenario was decoded into. Reordering it reorders what Instance emits
-// while the per-step field generators stay where they are, so step 0 would get
-// step 1's topic and step 0's fields.
-func (g *FlowGen) Steps() []scenario.FlowStep { return g.steps }
-
// correlationID resolves the correlation id for a flow instance from the
// first step's document.
//
diff --git a/internal/kafka/admin.go b/internal/kafka/admin.go
index a7a929c..18ed87e 100644
--- a/internal/kafka/admin.go
+++ b/internal/kafka/admin.go
@@ -217,16 +217,13 @@ func (a *Admin) waitForTopics(ctx context.Context, names []string, want bool) er
deadline := time.Now().Add(TopicReadyTimeout)
for {
+ // Metadata is fanned out, so topicsPresent can be a partial failure. Treat an
+ // error as "not settled yet" and retry until the deadline rather than failing the
+ // run on one transient shard error.
present, err := a.topicsPresent(ctx, names)
- if err != nil {
- // Metadata is fanned out, so this can be a partial failure. Treat it as
- // "not settled yet" and retry until the deadline rather than failing the
- // run on one transient shard error.
- if time.Now().After(deadline) {
- return fmt.Errorf("listing topics: %w", describeShardErrors(err))
- }
- } else {
- pending := make([]string, 0, len(names))
+ var pending []string
+ if err == nil {
+ pending = make([]string, 0, len(names))
for _, n := range names {
if present[n] != want {
pending = append(pending, n)
@@ -235,14 +232,18 @@ func (a *Admin) waitForTopics(ctx context.Context, names []string, want bool) er
if len(pending) == 0 {
return nil
}
- if time.Now().After(deadline) {
- state := "appear"
- if !want {
- state = "disappear"
- }
- return fmt.Errorf("timed out after %s waiting for %s to %s",
- TopicReadyTimeout, strings.Join(pending, ", "), state)
+ }
+
+ if time.Now().After(deadline) {
+ if err != nil {
+ return fmt.Errorf("listing topics: %w", describeShardErrors(err))
+ }
+ state := "appear"
+ if !want {
+ state = "disappear"
}
+ return fmt.Errorf("timed out after %s waiting for %s to %s",
+ TopicReadyTimeout, strings.Join(pending, ", "), state)
}
select {
diff --git a/internal/kafka/admin_test.go b/internal/kafka/admin_test.go
index f25a519..857c748 100644
--- a/internal/kafka/admin_test.go
+++ b/internal/kafka/admin_test.go
@@ -191,7 +191,7 @@ func TestAdminEnsureTopicsRecreate(t *testing.T) {
}, false); err != nil {
t.Fatalf("EnsureTopics() without recreate = %v", err)
}
- if got := partitionCount(t, ctx, a, topic); got != 1 {
+ if got := partitionCount(t, a, topic); got != 1 {
t.Fatalf("partitions = %d without recreate, want the existing 1 to be left alone", got)
}
@@ -200,7 +200,7 @@ func TestAdminEnsureTopicsRecreate(t *testing.T) {
}, true); err != nil {
t.Fatalf("EnsureTopics() with recreate = %v", err)
}
- if got := partitionCount(t, ctx, a, topic); got != 4 {
+ if got := partitionCount(t, a, topic); got != 4 {
t.Fatalf("partitions = %d after recreate, want 4", got)
}
}
@@ -246,9 +246,9 @@ func TestAdminWaitForTopicsSeesFreshMetadata(t *testing.T) {
}
}
-func partitionCount(t *testing.T, ctx context.Context, a *Admin, topic string) int {
+func partitionCount(t *testing.T, a *Admin, topic string) int {
t.Helper()
- details, err := a.adm.ListTopics(ctx, topic)
+ details, err := a.adm.ListTopics(testCtx(t), topic)
if err != nil {
t.Fatalf("ListTopics(%q) = %v", topic, err)
}
diff --git a/internal/kafka/errors.go b/internal/kafka/errors.go
index 752dd18..2265bc7 100644
--- a/internal/kafka/errors.go
+++ b/internal/kafka/errors.go
@@ -2,13 +2,41 @@ package kafka
import "strings"
-// Explain turns a client or broker error into an actionable one-line hint by matching
-// substrings of the lowercased error text. Substring matching is fragile, but it covers the
-// messy transport-level failures that have no clean error code to switch on instead.
+// explainHints are the substring-to-hint rules Explain walks, in order; the first entry
+// with any substring present in the lowercased error text wins.
//
-// The ordering of the checks is load-bearing: "timed out" is tested before "ssl" so a TLS
-// handshake that merely timed out is reported as a timeout, and "unknown topic" before
-// "topicauthorization" for the same reason. Errors that match nothing are returned as-is.
+// The order is load-bearing: "timed out" sits before "ssl" so a TLS handshake that merely
+// timed out is reported as a timeout, "unauthorized" before "ssl" so an auth rejection on a
+// TLS connection is reported as an authorization failure, and "unknown topic" before
+// "topicauthorization" for the same reason.
+var explainHints = []struct {
+ subs []string
+ hint string
+}{
+ {[]string{"brokertransportfailure", "all brokers are down"},
+ "Cannot connect to broker. Check Kafka is running and bootstrap servers are correct."},
+ {[]string{"resolve", "unknown host", "nodename"},
+ "Cannot resolve broker hostname. Check bootstrap server addresses."},
+ {[]string{"connection refused"},
+ "Connection refused. Check that Kafka broker is running on the specified port."},
+ {[]string{"timed out", "timeout"},
+ "Connection timed out. Check network connectivity and firewall rules."},
+ {[]string{"authentication", "sasl"},
+ "Authentication failed. Check SASL username and password."},
+ {[]string{"unauthorized", "not authorized"},
+ "Not authorized. Check user permissions and ACLs."},
+ {[]string{"ssl", "certificate", "handshake"},
+ "SSL/TLS error. Check certificate paths and permissions."},
+ {[]string{"unknown topic", "topic not found"},
+ "Topic does not exist. Check topic name or create the topic first."},
+ {[]string{"topicauthorization"},
+ "Not authorized for topic. Check ACLs and permissions."},
+}
+
+// Explain turns a client or broker error into an actionable one-line hint by matching
+// substrings of the lowercased error text against explainHints. Substring matching is
+// fragile, but it covers the messy transport-level failures that have no clean error code
+// to switch on instead. Errors that match nothing are returned as-is.
func Explain(err error) string {
if err == nil {
return ""
@@ -16,37 +44,15 @@ func Explain(err error) string {
msg := err.Error()
low := strings.ToLower(msg)
- has := func(subs ...string) bool {
- for _, s := range subs {
+ for _, h := range explainHints {
+ for _, s := range h.subs {
if strings.Contains(low, s) {
- return true
+ return h.hint
}
}
- return false
}
-
- switch {
- case has("brokertransportfailure", "all brokers are down"):
- return "Cannot connect to broker. Check Kafka is running and bootstrap servers are correct."
- case has("resolve", "unknown host", "nodename"):
- return "Cannot resolve broker hostname. Check bootstrap server addresses."
- case has("connection refused"):
- return "Connection refused. Check that Kafka broker is running on the specified port."
- case has("timed out", "timeout"):
- return "Connection timed out. Check network connectivity and firewall rules."
- case has("authentication", "sasl"):
- return "Authentication failed. Check SASL username and password."
- case has("unauthorized", "not authorized"):
- return "Not authorized. Check user permissions and ACLs."
- case has("ssl", "certificate", "handshake"):
- return "SSL/TLS error. Check certificate paths and permissions."
- case has("unknown topic", "topic not found"):
- return "Topic does not exist. Check topic name or create the topic first."
- case has("topicauthorization"):
- return "Not authorized for topic. Check ACLs and permissions."
- case strings.Contains(low, "replication") && strings.Contains(low, "factor"):
+ if strings.Contains(low, "replication") && strings.Contains(low, "factor") {
return "Invalid replication factor. Cannot exceed the number of available brokers."
- default:
- return msg
}
+ return msg
}
diff --git a/internal/kafka/security_test.go b/internal/kafka/security_test.go
index 75ee897..f5e58c9 100644
--- a/internal/kafka/security_test.go
+++ b/internal/kafka/security_test.go
@@ -4,6 +4,7 @@ import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
+ "crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
@@ -235,7 +236,7 @@ func TestSecurityOptionsTLSFromPEMFiles(t *testing.T) {
if len(cfg.Certificates) != 1 {
t.Errorf("got %d client certificates, want 1", len(cfg.Certificates))
}
- if cfg.MinVersion < 0x0303 { // TLS 1.2
+ if cfg.MinVersion < tls.VersionTLS12 {
t.Errorf("MinVersion = %#x, want at least TLS 1.2", cfg.MinVersion)
}
})
diff --git a/internal/localcluster/compose_test.go b/internal/localcluster/compose_test.go
index c585f89..e5ae508 100644
--- a/internal/localcluster/compose_test.go
+++ b/internal/localcluster/compose_test.go
@@ -33,16 +33,25 @@ func newFakeRunner() *fakeRunner {
}
}
+// parseDockerArgv splits a compose argv such as "compose -p khaos -f FILE ps ..." into the
+// compose file and the verb that follows it. Both come back empty when there is no -f.
+func parseDockerArgv(args []string) (composeFile, verb string) {
+ for i, arg := range args {
+ if arg == "-f" && i+2 < len(args) {
+ return args[i+1], args[i+2]
+ }
+ }
+ return "", ""
+}
+
// subcommand extracts the verb from a docker argv: "compose -p khaos -f FILE ps ..."
// yields "ps", and a bare "ps --filter ..." yields "docker-ps".
func subcommand(args []string) string {
if len(args) > 0 && args[0] != "compose" {
return "docker-" + args[0]
}
- if len(args) > 5 {
- return args[5]
- }
- return ""
+ _, verb := parseDockerArgv(args)
+ return verb
}
func (f *fakeRunner) run(_ context.Context, args ...string) (string, string, error) {
@@ -199,8 +208,8 @@ func TestDownTearsDownRegistryBeforeCluster(t *testing.T) {
var downFiles []string
for _, call := range f.calls {
- if subcommand(call) == "down" {
- downFiles = append(downFiles, call[4])
+ if file, verb := parseDockerArgv(call); verb == "down" {
+ downFiles = append(downFiles, file)
}
}
want := []string{"/cache/khaos/compose/" + composeSRKRaft, "/cache/khaos/compose/" + composeKRaft}
@@ -322,10 +331,11 @@ func TestUpSkipsSchemaRegistryWhenAlreadyRunning(t *testing.T) {
var gotUpFiles []string
for _, call := range f.calls {
- if subcommand(call) != "up" {
+ file, verb := parseDockerArgv(call)
+ if verb != "up" {
continue
}
- if base := filepath.Base(call[4]); base != composeKRaft {
+ if base := filepath.Base(file); base != composeKRaft {
gotUpFiles = append(gotUpFiles, base)
}
if call[1] != "-p" || call[2] != ProjectName {
@@ -415,11 +425,8 @@ func TestBrokerActionsIssueTheirOwnVerb(t *testing.T) {
var verbs []string
for _, call := range f.calls {
- for i, arg := range call {
- // The subcommand is whatever follows the compose file.
- if arg == "-f" && i+2 < len(call) {
- verbs = append(verbs, call[i+2])
- }
+ if _, verb := parseDockerArgv(call); verb != "" {
+ verbs = append(verbs, verb)
}
}
if !slices.Contains(verbs, tt.verb) {
diff --git a/internal/localcluster/errors.go b/internal/localcluster/errors.go
index c281e19..0a3387e 100644
--- a/internal/localcluster/errors.go
+++ b/internal/localcluster/errors.go
@@ -50,33 +50,74 @@ func conflictingPort(stderr string) string {
return ""
}
-// classifyComposeError turns a failed docker invocation into a typed error.
-//
-// The last branch treats any stderr containing "not found" (case insensitive) as a missing
-// compose file, so e.g. `manifest ... not found` from a failed image pull is also reported
-// as ErrComposeFileNotFound rather than narrowed to the exact case. The wrapped stderr is
-// always included so the real cause is never lost.
-func classifyComposeError(action, composeFile, stderr string, err error) error {
- low := strings.ToLower(stderr)
+// composeFailure recognises one docker failure mode by substring-matching stderr.
+type composeFailure struct {
+ patterns []string // any one of these in stderr identifies the failure
+ fold bool // match against lowercased stderr
+ sentinel error
+ // detail renders what follows the sentinel in the returned error.
+ detail func(composeFile, stderr string) string
+}
- switch {
- case strings.Contains(stderr, "Cannot connect to the Docker daemon"),
- strings.Contains(stderr, "Is the docker daemon running"):
- return fmt.Errorf("%s: %w: %s", action, ErrDockerNotRunning, msgDockerNotRunning)
+// composeFailures is walked in order and the first match wins, so a stderr that mentions
+// both the daemon and a missing file is reported as the daemon problem, the actionable one.
+var composeFailures = []composeFailure{
+ {
+ patterns: []string{"Cannot connect to the Docker daemon", "Is the docker daemon running"},
+ sentinel: ErrDockerNotRunning,
+ detail: func(string, string) string { return msgDockerNotRunning },
+ },
+ {
+ patterns: []string{"port is already allocated"},
+ sentinel: ErrPortAllocated,
+ detail: portAllocatedDetail,
+ },
+ {
+ patterns: []string{"no such file or directory", "not found"},
+ fold: true,
+ sentinel: ErrComposeFileNotFound,
+ detail: func(composeFile, stderr string) string {
+ return composeFile + ": " + strings.TrimSpace(stderr)
+ },
+ },
+}
- case strings.Contains(stderr, "port is already allocated"):
- // The bundled stack also publishes 8080 (kafka-ui) and 8081 (schema-registry), so
- // a generic "port already allocated" message would send you hunting for a stray
- // Kafka when the actual clash is elsewhere. Name the real port when it can be
- // extracted, and always append what docker actually said.
- if port := conflictingPort(stderr); port != "" {
- return fmt.Errorf("%s: %w: port %s is already in use: %s",
- action, ErrPortAllocated, port, strings.TrimSpace(stderr))
+func (f composeFailure) matches(stderr string) bool {
+ if f.fold {
+ stderr = strings.ToLower(stderr)
+ }
+ for _, p := range f.patterns {
+ if strings.Contains(stderr, p) {
+ return true
}
- return fmt.Errorf("%s: %w: %s: %s", action, ErrPortAllocated, msgPortAllocated, strings.TrimSpace(stderr))
+ }
+ return false
+}
- case strings.Contains(low, "no such file or directory"), strings.Contains(low, "not found"):
- return fmt.Errorf("%s: %w: %s: %s", action, ErrComposeFileNotFound, composeFile, strings.TrimSpace(stderr))
+// portAllocatedDetail names the port docker actually failed to bind.
+//
+// The bundled stack also publishes 8080 (kafka-ui) and 8081 (schema-registry), so a
+// generic "port already allocated" message would send you hunting for a stray Kafka when
+// the actual clash is elsewhere. Name the real port when it can be extracted, and always
+// append what docker actually said.
+func portAllocatedDetail(_, stderr string) string {
+ if port := conflictingPort(stderr); port != "" {
+ return fmt.Sprintf("port %s is already in use: %s", port, strings.TrimSpace(stderr))
+ }
+ return msgPortAllocated + ": " + strings.TrimSpace(stderr)
+}
+
+// classifyComposeError turns a failed docker invocation into a typed error.
+//
+// The last entry of composeFailures treats any stderr containing "not found" (case
+// insensitive) as a missing compose file, so e.g. `manifest ... not found` from a failed
+// image pull is also reported as ErrComposeFileNotFound rather than narrowed to the exact
+// case. The wrapped stderr is always included so the real cause is never lost.
+func classifyComposeError(action, composeFile, stderr string, err error) error {
+ for _, f := range composeFailures {
+ if f.matches(stderr) {
+ return fmt.Errorf("%s: %w: %s", action, f.sentinel, f.detail(composeFile, stderr))
+ }
}
if stderr = strings.TrimSpace(stderr); stderr != "" {
diff --git a/internal/localcluster/status.go b/internal/localcluster/status.go
index aefe27e..f457a32 100644
--- a/internal/localcluster/status.go
+++ b/internal/localcluster/status.go
@@ -116,36 +116,47 @@ func parsePS(stdout string) []ServiceStatus {
// and JMX always on jmxTargetPort. Non-broker services publish a single port, and the
// lowest published port is chosen so the result stays deterministic.
func selectPublishedPort(service string, pubs []composePublisher) int {
- isBroker := strings.HasPrefix(service, "kafka-") && service != kafkaUIServiceName
+ if isBroker(service) {
+ return brokerClientPort(pubs)
+ }
+ return lowestPublishedPort(pubs)
+}
+
+// isBroker reports whether a compose service is one of the Kafka brokers: those named
+// "kafka-*" other than kafka-ui.
+func isBroker(service string) bool {
+ return strings.HasPrefix(service, "kafka-") && service != kafkaUIServiceName
+}
+
+// brokerClientPort returns the published port whose container side is a known client
+// listener, or, when no publisher advertises one, the lowest non-JMX published port
+// rather than reporting nothing.
+func brokerClientPort(pubs []composePublisher) int {
+ for _, p := range pubs {
+ if p.PublishedPort > 0 && kafkaClientPorts[p.TargetPort] {
+ return p.PublishedPort
+ }
+ }
+ var nonJMX []composePublisher
+ for _, p := range pubs {
+ if p.TargetPort != jmxTargetPort {
+ nonJMX = append(nonJMX, p)
+ }
+ }
+ return lowestPublishedPort(nonJMX)
+}
+// lowestPublishedPort returns the smallest positive published port, or 0.
+func lowestPublishedPort(pubs []composePublisher) int {
best := 0
for _, p := range pubs {
if p.PublishedPort <= 0 {
continue
}
- if isBroker {
- if p.TargetPort == jmxTargetPort || !kafkaClientPorts[p.TargetPort] {
- continue
- }
- return p.PublishedPort
- }
if best == 0 || p.PublishedPort < best {
best = p.PublishedPort
}
}
-
- if isBroker {
- // No publisher advertised a known client port. Fall back to the lowest
- // non-JMX published port rather than reporting nothing.
- for _, p := range pubs {
- if p.PublishedPort <= 0 || p.TargetPort == jmxTargetPort {
- continue
- }
- if best == 0 || p.PublishedPort < best {
- best = p.PublishedPort
- }
- }
- }
return best
}
@@ -156,10 +167,7 @@ func selectPublishedPort(service string, pubs []composePublisher) int {
func brokerAddresses(statuses []ServiceStatus) string {
var brokers []string
for _, s := range statuses {
- if !strings.HasPrefix(s.Service, "kafka-") || s.Service == kafkaUIServiceName {
- continue
- }
- if s.PublishedPort <= 0 {
+ if !isBroker(s.Service) || s.PublishedPort <= 0 {
continue
}
brokers = append(brokers, hostPort(s.PublishedPort))
diff --git a/internal/scenario/decode.go b/internal/scenario/decode.go
index 6125494..4dd6355 100644
--- a/internal/scenario/decode.go
+++ b/internal/scenario/decode.go
@@ -314,7 +314,7 @@ func decodeIncident(n *yaml.Node) (Incident, error) {
}, nil
case IncidentRebalanceConsumer:
return RebalanceConsumer{Target: r.Target.consumer(), Schedule: sched}, nil
- case IncidentIncreaseConsumerDlay:
+ case IncidentIncreaseConsumerDelay:
return IncreaseConsumerDelay{
DelayMS: r.DelayMS,
Target: r.Target.consumer(),
diff --git a/internal/scenario/decode_test.go b/internal/scenario/decode_test.go
index 4089c5b..37d99d7 100644
--- a/internal/scenario/decode_test.go
+++ b/internal/scenario/decode_test.go
@@ -347,7 +347,7 @@ incidents:
`)
wantTypes := []string{
IncidentStopBroker, IncidentStartBroker, IncidentPauseConsumer,
- IncidentRebalanceConsumer, IncidentIncreaseConsumerDlay, IncidentChangeProducerRate,
+ IncidentRebalanceConsumer, IncidentIncreaseConsumerDelay, IncidentChangeProducerRate,
}
if len(sc.Incidents) != len(wantTypes) {
t.Fatalf("want %d incidents, got %d", len(wantTypes), len(sc.Incidents))
diff --git a/internal/scenario/incident.go b/internal/scenario/incident.go
index c00a793..ef39a5e 100644
--- a/internal/scenario/incident.go
+++ b/internal/scenario/incident.go
@@ -10,12 +10,12 @@ import (
//
// This is a closed set; an unrecognised `type:` is a hard error.
const (
- IncidentStopBroker = "stop_broker"
- IncidentStartBroker = "start_broker"
- IncidentPauseConsumer = "pause_consumer"
- IncidentRebalanceConsumer = "rebalance_consumer"
- IncidentIncreaseConsumerDlay = "increase_consumer_delay"
- IncidentChangeProducerRate = "change_producer_rate"
+ IncidentStopBroker = "stop_broker"
+ IncidentStartBroker = "start_broker"
+ IncidentPauseConsumer = "pause_consumer"
+ IncidentRebalanceConsumer = "rebalance_consumer"
+ IncidentIncreaseConsumerDelay = "increase_consumer_delay"
+ IncidentChangeProducerRate = "change_producer_rate"
)
// Schedule controls when an incident fires.
@@ -413,7 +413,7 @@ type IncreaseConsumerDelay struct {
Schedule Schedule
}
-func (i IncreaseConsumerDelay) Type() string { return IncidentIncreaseConsumerDlay }
+func (i IncreaseConsumerDelay) Type() string { return IncidentIncreaseConsumerDelay }
func (i IncreaseConsumerDelay) Sched() Schedule { return i.Schedule }
func (i IncreaseConsumerDelay) Commands(ctx *Context) []Command {
diff --git a/internal/scenario/validate.go b/internal/scenario/validate.go
index e35f445..c495369 100644
--- a/internal/scenario/validate.go
+++ b/internal/scenario/validate.go
@@ -8,10 +8,12 @@ import (
"go.yaml.in/yaml/v3"
)
-// This file validates a scenario document: top level and topics, then fields
-// recursively, then flows and steps, then incidents.
+// This file holds the validator and its shared helpers plus the top-level document
+// walk; the regions it dispatches to live beside it: validate_topic.go (topics and
+// their configs), validate_field.go (field recursion), validate_flow.go (flows and
+// steps) and validate_incident.go (incidents and groups).
//
-// It runs against the raw yaml.Node tree, before any typed decoding, so a scenario
+// Validation runs against the raw yaml.Node tree, before any typed decoding, so a scenario
// author gets every problem in one pass instead of one per edit-run cycle. The typed
// decode in decode.go only happens once this pass reports no errors.
//
@@ -76,7 +78,7 @@ var (
validCorrelationTypes = newValueSet(CorrelationUUID, CorrelationFieldRef)
validIncidentTypeNames = newValueSet(
IncidentStopBroker, IncidentStartBroker, IncidentPauseConsumer,
- IncidentRebalanceConsumer, IncidentIncreaseConsumerDlay, IncidentChangeProducerRate,
+ IncidentRebalanceConsumer, IncidentIncreaseConsumerDelay, IncidentChangeProducerRate,
)
// sortedFieldTypes renders ValidFieldTypes for messages.
sortedFieldTypes = func() valueSet {
@@ -188,937 +190,3 @@ func (v *validator) scenario(n *yaml.Node) {
}
}
}
-
-// topics validates the topic list and emits the schemaless-mode warning.
-//
-// The warning names the data_format of the LAST avro/protobuf topic seen, since the
-// scan reassigns schemaFormatName on every matching topic in the loop.
-func (v *validator) topics(n *yaml.Node, hasSchemaRegistry bool) {
- if !isSequence(n) {
- v.errf(n, "topics", "Field 'topics' must be a list")
- return
- }
- schemaFormatName := ""
- var lastFormatNode *yaml.Node
- for i, topic := range seqItems(n) {
- path := index("topics", i)
- v.topic(topic, path)
- format := mapGet(mapGet(topic, "message_schema"), "data_format")
- if text := scalarText(format); text == "avro" || text == "protobuf" {
- schemaFormatName = text
- lastFormatNode = format
- }
- }
- if schemaFormatName != "" && !hasSchemaRegistry {
- v.warnf(lastFormatNode, "schema_registry",
- "Using %s without Schema Registry (schemaless mode)", title(schemaFormatName))
- }
-}
-
-// title upper-cases the first letter of a single-word format name ("avro" -> "Avro",
-// "protobuf" -> "Protobuf").
-func title(s string) string {
- if s == "" {
- return s
- }
- return strings.ToUpper(s[:1]) + s[1:]
-}
-
-// topic validates one entry of `topics:`.
-func (v *validator) topic(n *yaml.Node, path string) {
- if !isMapping(n) {
- v.errf(n, path, "Topic must be an object/dict")
- return
- }
- v.knownKeys(n, path,
- "name", "partitions", "replication_factor", "num_producers", "num_consumer_groups",
- "consumers_per_group", "producer_rate", "consumer_delay_ms", "message_schema",
- "producer_config", "consumer_config", "schema_provider", "subject_name")
-
- switch name := mapGet(n, "name"); {
- case name == nil:
- v.errf(n, join(path, "name"), "Missing required field 'name'")
- case !isString(name):
- v.errf(name, join(path, "name"), "Field 'name' must be a string")
- }
-
- // partitions: the >100 case is a warning, not an error.
- if p := mapGet(n, "partitions"); p != nil {
- if count, ok := intValue(p); !ok || count < 1 {
- v.errf(p, join(path, "partitions"), "Field 'partitions' must be a positive integer")
- } else if count > 100 {
- v.warnf(p, join(path, "partitions"),
- "High partition count (%d) may impact performance", count)
- }
- }
-
- // replication_factor: the upper bound is a cluster assumption (see Cluster).
- if rf := mapGet(n, "replication_factor"); rf != nil {
- if factor, ok := intValue(rf); !ok || factor < 1 {
- v.errf(rf, join(path, "replication_factor"),
- "Field 'replication_factor' must be a positive integer")
- } else if factor > Cluster.MaxReplicationFactor() {
- v.errf(rf, join(path, "replication_factor"),
- "Replication factor cannot exceed %d (cluster has %d brokers)",
- Cluster.MaxReplicationFactor(), len(Cluster.Brokers))
- }
- }
-
- // num_producers is non-negative, unlike the other counts: zero producers is a
- // legitimate consume-only topic.
- v.intAtLeast(n, path, "num_producers", 0, "Field 'num_producers' must be a non-negative integer")
- v.intAtLeast(n, path, "num_consumer_groups", 1, "Field 'num_consumer_groups' must be a positive integer")
- v.intAtLeast(n, path, "consumers_per_group", 1, "Field 'consumers_per_group' must be a positive integer")
-
- if rate := mapGet(n, "producer_rate"); rate != nil {
- if r, ok := floatValue(rate); !ok || r <= 0 {
- v.errf(rate, join(path, "producer_rate"), "Field 'producer_rate' must be a positive number")
- }
- }
- v.intAtLeast(n, path, "consumer_delay_ms", 0, "Field 'consumer_delay_ms' must be a non-negative integer")
-
- // schema_provider is read before message_schema because it changes whether fields
- // are required or forbidden.
- providerNode := mapGet(n, "schema_provider")
- provider := defaultSchemaProvider
- if providerNode != nil {
- provider = scalarText(providerNode)
- }
-
- if ms := mapGet(n, "message_schema"); ms != nil {
- v.messageSchema(ms, join(path, "message_schema"), provider)
- }
- if pc := mapGet(n, "producer_config"); pc != nil {
- v.producerConfig(pc, join(path, "producer_config"))
- }
- if cc := mapGet(n, "consumer_config"); cc != nil {
- v.consumerConfig(cc, join(path, "consumer_config"))
- }
-
- if !validSchemaProviders.has(provider) {
- v.errf(providerNode, join(path, "schema_provider"),
- "Invalid schema_provider '%s'. Valid values: %s", provider, validSchemaProviders)
- }
-
- // registry provider: subject_name required, inline fields forbidden.
- if provider == "registry" {
- switch subject := mapGet(n, "subject_name"); {
- case subject == nil:
- v.errf(n, join(path, "subject_name"),
- "Field 'subject_name' is required when schema_provider is 'registry'")
- case !isString(subject):
- v.errf(subject, join(path, "subject_name"), "Field 'subject_name' must be a string")
- }
- if fields := mapGet(mapGet(n, "message_schema"), "fields"); fields != nil && len(seqItems(fields)) > 0 {
- v.errf(fields, path,
- "Cannot define 'message_schema.fields' when schema_provider is 'registry' "+
- "(schema will be fetched from Schema Registry)")
- }
- }
-}
-
-// intAtLeast is the shape shared by the "must be a (non-)negative integer" checks: the
-// key is optional, but when present it must be an int no smaller than lo.
-func (v *validator) intAtLeast(n *yaml.Node, path, key string, lo int, message string) {
- node := mapGet(n, key)
- if node == nil {
- return
- }
- if value, ok := intValue(node); !ok || value < lo {
- v.errf(node, join(path, key), "%s", message)
- }
-}
-
-// messageSchema validates one `message_schema:` block.
-func (v *validator) messageSchema(n *yaml.Node, path, provider string) {
- if !isMapping(n) {
- v.errf(n, path, "message_schema must be an object/dict")
- return
- }
- v.knownKeys(n, path, "key_distribution", "key_cardinality", "min_size_bytes",
- "max_size_bytes", "data_format", "fields")
-
- if kd := mapGet(n, "key_distribution"); kd != nil {
- if text := scalarText(kd); !validKeyDistributions.has(text) {
- v.errf(kd, join(path, "key_distribution"),
- "Invalid key_distribution '%s'. Valid values: %s", text, validKeyDistributions)
- }
- }
- v.intAtLeast(n, path, "key_cardinality", 1, "Field 'key_cardinality' must be a positive integer")
-
- if df := mapGet(n, "data_format"); df != nil {
- text := scalarText(df)
- if !validDataFormats.has(text) {
- v.errf(df, join(path, "data_format"),
- "Invalid data_format '%s'. Valid values: %s", text, validDataFormats)
- }
- // Binary formats need a schema to encode against. The registry provider
- // supplies one at runtime, so the requirement only applies inline.
- fields := mapGet(n, "fields")
- hasFields := fields != nil && len(seqItems(fields)) > 0
- if provider == "inline" && (text == "avro" || text == "protobuf") && !hasFields {
- v.errf(df, join(path, "fields"),
- "data_format '%s' requires 'fields' to be defined "+
- "(or use schema_provider: registry to fetch from Schema Registry)", text)
- }
- }
-
- v.intAtLeast(n, path, "min_size_bytes", 1, "Field 'min_size_bytes' must be a positive integer")
- v.intAtLeast(n, path, "max_size_bytes", 1, "Field 'max_size_bytes' must be a positive integer")
- // The pairing is checked against the defaults when a bound is omitted, so setting
- // only min_size_bytes: 900 is an error against the default max of 500.
- v.pairing(n, path, "min_size_bytes", "max_size_bytes", defaultMinSizeBytes, defaultMaxSizeBytes,
- "min_size_bytes cannot be greater than max_size_bytes")
-
- if fields := mapGet(n, "fields"); fields != nil {
- v.fields(fields, join(path, "fields"))
- }
-}
-
-// pairing reproduces the four "min cannot be greater than max" checks, each of which
-// falls back to the model default for an omitted bound and skips entirely when either
-// present value is not an integer.
-func (v *validator) pairing(n *yaml.Node, path, minKey, maxKey string, minDefault, maxDefault int, message string) {
- minNode, maxNode := mapGet(n, minKey), mapGet(n, maxKey)
- minVal, maxVal := minDefault, maxDefault
- if minNode != nil {
- value, ok := intValue(minNode)
- if !ok {
- return
- }
- minVal = value
- }
- if maxNode != nil {
- value, ok := intValue(maxNode)
- if !ok {
- return
- }
- maxVal = value
- }
- if minVal > maxVal {
- v.errf(cmpNode(minNode, n), path, "%s", message)
- }
-}
-
-// cmpNode picks the most specific node available to hang a pairing error on.
-func cmpNode(preferred, fallback *yaml.Node) *yaml.Node {
- if preferred != nil {
- return preferred
- }
- return fallback
-}
-
-// schemaRegistry validates a top-level `schema_registry:` block.
-func (v *validator) schemaRegistry(n *yaml.Node, path string) {
- if !isMapping(n) {
- v.errf(n, path, "schema_registry must be an object/dict")
- return
- }
- v.knownKeys(n, path, "url")
- switch url := mapGet(n, "url"); {
- case url == nil:
- v.errf(n, join(path, "url"), "Missing required field 'url'")
- case !isString(url):
- v.errf(url, join(path, "url"), "Field 'url' must be a string")
- case !strings.HasPrefix(url.Value, "http://") && !strings.HasPrefix(url.Value, "https://"):
- v.errf(url, join(path, "url"), "Field 'url' must be a valid HTTP(S) URL")
- }
-}
-
-// producerConfig validates one `producer_config:` block.
-func (v *validator) producerConfig(n *yaml.Node, path string) {
- if !isMapping(n) {
- v.errf(n, path, "producer_config must be an object/dict")
- return
- }
- v.knownKeys(n, path, "batch_size", "linger_ms", "acks", "compression_type", "duplicate_rate")
-
- v.intAtLeast(n, path, "batch_size", 0, "Field 'batch_size' must be a non-negative integer")
- v.intAtLeast(n, path, "linger_ms", 0, "Field 'linger_ms' must be a non-negative integer")
-
- // acks is compared as a string, so both `acks: 1` and `acks: "1"` are accepted.
- if acks := mapGet(n, "acks"); acks != nil {
- text := scalarText(acks)
- if !validAcks.has(text) {
- v.errf(acks, join(path, "acks"), "Invalid acks '%s'. Valid values: %s", text, validAcks)
- }
- }
- if ct := mapGet(n, "compression_type"); ct != nil {
- if text := scalarText(ct); !validCompressionTypes.has(text) {
- v.errf(ct, join(path, "compression_type"),
- "Invalid compression_type '%s'. Valid values: %s", text, validCompressionTypes)
- }
- }
- v.rate01(n, path, "duplicate_rate",
- "Field 'duplicate_rate' must be a number between 0.0 and 1.0",
- "High duplicate rate (%s) will produce many duplicate messages")
-}
-
-// consumerConfig validates one `consumer_config:` block.
-func (v *validator) consumerConfig(n *yaml.Node, path string) {
- if !isMapping(n) {
- v.errf(n, path, "consumer_config must be an object/dict")
- return
- }
- v.knownKeys(n, path, "failure_rate", "commit_failure_rate", "on_failure", "max_retries")
-
- v.rate01(n, path, "failure_rate",
- "Field 'failure_rate' must be a number between 0.0 and 1.0",
- "High failure rate (%s) may cause significant message loss")
- v.rate01(n, path, "commit_failure_rate",
- "Field 'commit_failure_rate' must be a number between 0.0 and 1.0",
- "High commit failure rate (%s) may cause significant reprocessing")
-
- if of := mapGet(n, "on_failure"); of != nil {
- text := scalarText(of)
- if !validOnFailureActions.has(text) {
- v.errf(of, join(path, "on_failure"),
- "Invalid on_failure '%s'. Valid values: %s", text, validOnFailureActions)
- } else if text == "dlq" {
- v.warnf(of, join(path, "on_failure"),
- "DLQ mode enabled - ensure DLQ topics exist or are auto-created")
- }
- }
- v.intAtLeast(n, path, "max_retries", 0, "Field 'max_retries' must be a non-negative integer")
-}
-
-// rate01 is the shape shared by the three [0,1] probability keys: out of range is an
-// error, and anything above 0.5 is a warning rendered as a percentage.
-func (v *validator) rate01(n *yaml.Node, path, key, errMessage, warnFormat string) {
- node := mapGet(n, key)
- if node == nil {
- return
- }
- rate, ok := floatValue(node)
- if !ok || rate < 0 || rate > 1 {
- v.errf(node, join(path, key), "%s", errMessage)
- return
- }
- if rate > 0.5 {
- v.warnf(node, join(path, key), warnFormat, percent(rate))
- }
-}
-
-// percent renders a rate as a whole-number percentage, e.g. 0.75 -> "75%".
-func percent(rate float64) string { return fmt.Sprintf("%.0f%%", rate*100) }
-
-func (v *validator) fields(n *yaml.Node, path string) {
- if !isSequence(n) {
- v.errf(n, path, "fields must be a list")
- return
- }
- for i, f := range seqItems(n) {
- v.field(f, index(path, i), false)
- }
-}
-
-// field validates one field definition, recursing into nested objects and array items.
-//
-// asItem distinguishes a named field from an array's `items:` schema, which differ in
-// two ways preserved verbatim: an array item needs no `name`, and an array item of type
-// faker is NOT checked for a `provider`, because the dispatch below skips fakerField
-// when asItem is set.
-//
-// A YAML anchor can make a field definition contain itself:
-//
-// fields:
-// - &f
-// name: a
-// type: array
-// items: *f
-//
-// Without a guard that recurses forever, appending another ".items" to the diagnostic
-// path on each pass until the process is killed. Nodes on the current recursion stack
-// are therefore tracked and re-entry is reported as an error. A finite tree, however
-// deeply nested, is unaffected: only an alias can revisit a node.
-func (v *validator) field(n *yaml.Node, path string, asItem bool) {
- n = resolveNode(n)
- if v.visiting[n] {
- v.errf(n, path, "Field definition refers to itself through a YAML anchor")
- return
- }
- if v.visiting == nil {
- v.visiting = make(map[*yaml.Node]bool)
- }
- v.visiting[n] = true
- defer delete(v.visiting, n)
-
- if !isMapping(n) {
- if asItem {
- v.errf(n, path, "Array item must be an object/dict")
- } else {
- v.errf(n, path, "Field must be an object/dict")
- }
- return
- }
- v.knownKeys(n, path, "name", "type", "min", "max", "min_length", "max_length",
- "cardinality", "values", "fields", "items", "min_items", "max_items",
- "provider", "locale")
-
- if !asItem {
- switch name := mapGet(n, "name"); {
- case name == nil:
- v.errf(n, join(path, "name"), "Missing required field 'name'")
- case !isString(name):
- v.errf(name, join(path, "name"), "Field 'name' must be a string")
- }
- }
-
- typeNode := mapGet(n, "type")
- if typeNode == nil {
- v.errf(n, join(path, "type"), "Missing required field 'type'")
- return
- }
- if !isString(typeNode) {
- v.errf(typeNode, join(path, "type"), "Field 'type' must be a string")
- return
- }
- fieldType := typeNode.Value
- if !ValidFieldTypes[fieldType] {
- v.errf(typeNode, join(path, "type"),
- "Unknown field type '%s'. Valid types: %s", fieldType, sortedFieldTypes)
- return
- }
-
- switch fieldType {
- case FieldString:
- v.stringField(n, path)
- case FieldInt:
- v.numericRange(n, path)
- v.cardinality(n, path)
- case FieldFloat:
- // No cardinality check for floats.
- v.numericRange(n, path)
- case FieldEnum:
- v.enumField(n, path)
- case FieldObject:
- v.objectField(n, path)
- case FieldArray:
- v.arrayField(n, path)
- case FieldFaker:
- if !asItem {
- v.fakerField(n, path)
- }
- }
-}
-
-// stringField validates the string-only constraints.
-func (v *validator) stringField(n *yaml.Node, path string) {
- v.intAtLeast(n, path, "min_length", 0, "Field 'min_length' must be a non-negative integer")
- v.intAtLeast(n, path, "max_length", 1, "Field 'max_length' must be a positive integer")
- // The defaults here (0 and 100) are the validator's own; the field model has no
- // length defaults at all.
- v.pairing(n, path, "min_length", "max_length", 0, 100,
- "min_length cannot be greater than max_length")
- v.cardinality(n, path)
-}
-
-// cardinality validates the shared `cardinality:` key.
-func (v *validator) cardinality(n *yaml.Node, path string) {
- v.intAtLeast(n, path, "cardinality", 1, "Field 'cardinality' must be a positive integer")
-}
-
-// numericRange validates min/max: they may be int or float, and are only compared when
-// both are present.
-func (v *validator) numericRange(n *yaml.Node, path string) {
- minNode, maxNode := mapGet(n, "min"), mapGet(n, "max")
- minOK, maxOK := true, true
- if minNode != nil && !isNumber(minNode) {
- v.errf(minNode, join(path, "min"), "Field 'min' must be a number")
- minOK = false
- }
- if maxNode != nil && !isNumber(maxNode) {
- v.errf(maxNode, join(path, "max"), "Field 'max' must be a number")
- maxOK = false
- }
- if minNode == nil || maxNode == nil || !minOK || !maxOK {
- return
- }
- minVal, _ := floatValue(minNode)
- maxVal, _ := floatValue(maxNode)
- if minVal > maxVal {
- v.errf(minNode, path, "min cannot be greater than max")
- }
-}
-
-// enumField validates an enum field's `values:` list.
-func (v *validator) enumField(n *yaml.Node, path string) {
- values := mapGet(n, "values")
- if values == nil {
- v.errf(n, join(path, "values"), "Enum field requires 'values' list")
- return
- }
- if !isSequence(values) {
- v.errf(values, join(path, "values"), "Field 'values' must be a list")
- return
- }
- items := seqItems(values)
- if len(items) == 0 {
- v.errf(values, join(path, "values"), "Enum must have at least one value")
- }
- for i, item := range items {
- if !isString(item) {
- v.errf(item, index(join(path, "values"), i), "Enum values must be strings")
- }
- }
-}
-
-// objectField validates an object field's nested `fields:` list.
-func (v *validator) objectField(n *yaml.Node, path string) {
- fields := mapGet(n, "fields")
- if fields == nil {
- v.errf(n, join(path, "fields"), "Object field requires 'fields' list")
- return
- }
- if !isSequence(fields) {
- v.errf(fields, join(path, "fields"), "Field 'fields' must be a list")
- return
- }
- items := seqItems(fields)
- if len(items) == 0 {
- v.errf(fields, join(path, "fields"), "Object must have at least one field")
- }
- // Nested object fields are full fields, so they do need a name.
- for i, nested := range items {
- v.field(nested, index(join(path, "fields"), i), false)
- }
-}
-
-// arrayField validates an array field's `items:` schema and length bounds.
-func (v *validator) arrayField(n *yaml.Node, path string) {
- items := mapGet(n, "items")
- if items == nil {
- v.errf(n, join(path, "items"), "Array field requires 'items' schema")
- return
- }
- if !isMapping(items) {
- v.errf(items, join(path, "items"), "Field 'items' must be an object/dict")
- return
- }
- v.intAtLeast(n, path, "min_items", 0, "Field 'min_items' must be a non-negative integer")
- v.intAtLeast(n, path, "max_items", 1, "Field 'max_items' must be a positive integer")
- v.pairing(n, path, "min_items", "max_items", defaultMinItems, defaultMaxItems,
- "min_items cannot be greater than max_items")
- v.field(items, join(path, "items"), true)
-}
-
-// fakerField validates a faker field's `provider:`/`locale:` keys.
-func (v *validator) fakerField(n *yaml.Node, path string) {
- provider := mapGet(n, "provider")
- if provider == nil {
- v.errf(n, join(path, "provider"), "Faker field requires 'provider'")
- return
- }
- if !isString(provider) {
- v.errf(provider, join(path, "provider"), "Field 'provider' must be a string")
- return
- }
- if locale := mapGet(n, "locale"); locale != nil && !isString(locale) {
- v.errf(locale, join(path, "locale"), "Field 'locale' must be a string")
- }
-}
-
-func (v *validator) flows(n *yaml.Node, path string) {
- if !isSequence(n) {
- v.errf(n, path, "Field 'flows' must be a list")
- return
- }
- for i, f := range seqItems(n) {
- v.flow(f, index(path, i))
- }
-}
-
-// flow validates one entry of `flows:`.
-func (v *validator) flow(n *yaml.Node, path string) {
- if !isMapping(n) {
- v.errf(n, path, "Flow must be an object/dict")
- return
- }
- v.knownKeys(n, path, "name", "rate", "steps", "correlation")
-
- switch name := mapGet(n, "name"); {
- case name == nil:
- v.errf(n, join(path, "name"), "Missing required field 'name'")
- case !isString(name):
- v.errf(name, join(path, "name"), "Field 'name' must be a string")
- }
-
- if rate := mapGet(n, "rate"); rate != nil {
- if r, ok := floatValue(rate); !ok || r <= 0 {
- v.errf(rate, join(path, "rate"), "Field 'rate' must be a positive number")
- }
- }
- if corr := mapGet(n, "correlation"); corr != nil {
- v.correlation(corr, join(path, "correlation"))
- }
-
- steps := mapGet(n, "steps")
- if steps == nil {
- v.errf(n, join(path, "steps"), "Missing required field 'steps'")
- return
- }
- if !isSequence(steps) {
- v.errf(steps, join(path, "steps"), "Field 'steps' must be a list")
- return
- }
- items := seqItems(steps)
- // A one-step flow is legal but pointless -- warning, not error.
- if len(items) < 2 {
- v.warnf(steps, join(path, "steps"),
- "Flow has fewer than 2 steps - consider using regular topics instead")
- }
- for i, step := range items {
- v.flowStep(step, index(join(path, "steps"), i), i == 0)
- }
-}
-
-// correlation validates a `correlation:` block. field_ref without a field name is the
-// one hard error here.
-func (v *validator) correlation(n *yaml.Node, path string) {
- if !isMapping(n) {
- v.errf(n, path, "correlation must be an object/dict")
- return
- }
- v.knownKeys(n, path, "type", "field")
-
- corrType := defaultCorrelationType
- typeNode := mapGet(n, "type")
- if typeNode != nil {
- corrType = scalarText(typeNode)
- }
- if !validCorrelationTypes.has(corrType) {
- v.errf(cmpNode(typeNode, n), join(path, "type"),
- "Invalid correlation type '%s'. Valid types: %s", corrType, validCorrelationTypes)
- }
- if corrType == CorrelationFieldRef {
- switch fieldNode := mapGet(n, "field"); {
- case fieldNode == nil:
- v.errf(n, join(path, "field"),
- "Correlation type 'field_ref' requires 'field' to be specified")
- case !isString(fieldNode):
- v.errf(fieldNode, join(path, "field"), "Field 'field' must be a string")
- }
- }
-}
-
-// flowStep validates one entry of a flow's `steps:` list.
-func (v *validator) flowStep(n *yaml.Node, path string, isFirst bool) {
- if !isMapping(n) {
- v.errf(n, path, "Step must be an object/dict")
- return
- }
- v.knownKeys(n, path, "topic", "event_type", "delay_ms", "fields", "consumers")
-
- switch topic := mapGet(n, "topic"); {
- case topic == nil:
- v.errf(n, join(path, "topic"), "Missing required field 'topic'")
- case !isString(topic):
- v.errf(topic, join(path, "topic"), "Field 'topic' must be a string")
- }
- switch event := mapGet(n, "event_type"); {
- case event == nil:
- v.errf(n, join(path, "event_type"), "Missing required field 'event_type'")
- case !isString(event):
- v.errf(event, join(path, "event_type"), "Field 'event_type' must be a string")
- }
-
- if delay := mapGet(n, "delay_ms"); delay != nil {
- if ms, ok := intValue(delay); !ok || ms < 0 {
- v.errf(delay, join(path, "delay_ms"), "Field 'delay_ms' must be a non-negative integer")
- }
- // The range check above and the first-step warning below are independent
- // checks against the raw value, not chained as an else-branch: a first-step
- // `delay_ms: 1.5` produces BOTH the range error and this warning. Reading the
- // value as a float here (rather than only as an int) is what surfaces the
- // warning even when the range check already failed. A non-numeric delay_ms
- // fails the isNum check below, so it produces the range error alone.
- if value, isNum := floatValue(delay); isFirst && isNum && value > 0 {
- v.warnf(delay, join(path, "delay_ms"),
- "First step has delay_ms - delay applies before flow starts")
- }
- }
-
- if fields := mapGet(n, "fields"); fields != nil {
- v.fields(fields, join(path, "fields"))
- }
- if consumers := mapGet(n, "consumers"); consumers != nil {
- v.stepConsumers(consumers, join(path, "consumers"))
- }
-}
-
-// stepConsumers validates a step's `consumers:` block.
-func (v *validator) stepConsumers(n *yaml.Node, path string) {
- if !isMapping(n) {
- v.errf(n, path, "consumers must be an object/dict")
- return
- }
- v.knownKeys(n, path, "groups", "per_group", "delay_ms")
- v.intAtLeast(n, path, "groups", 1, "Field 'groups' must be a positive integer")
- v.intAtLeast(n, path, "per_group", 1, "Field 'per_group' must be a positive integer")
- v.intAtLeast(n, path, "delay_ms", 0, "Field 'delay_ms' must be a non-negative integer")
-}
-
-// incidentKeys is the union of every key any incident type reads, plus `group`.
-var incidentKeys = []string{
- "type", "group", "at_seconds", "every_seconds", "initial_delay_seconds",
- "target", "broker", "duration_seconds", "delay_ms", "rate",
-}
-
-// incident validates one entry of the top-level `incidents:` list, which is either a
-// standalone incident or a group wrapper.
-func (v *validator) incident(n *yaml.Node, path string) {
- if !isMapping(n) {
- v.errf(n, path, "Incident must be an object/dict")
- return
- }
- // A `group` key makes the whole entry a group and nothing else on it is read.
- if group := mapGet(n, "group"); group != nil {
- v.incidentGroup(group, join(path, "group"))
- return
- }
- v.knownKeys(n, path, incidentKeys...)
-
- incidentType, ok := v.incidentType(n, path)
- if !ok {
- return
- }
-
- // Standalone incidents need a schedule; group members do not.
- at, every := mapGet(n, "at_seconds"), mapGet(n, "every_seconds")
- if at == nil && every == nil {
- v.errf(n, path, "Incident must have either 'at_seconds' or 'every_seconds'")
- }
- if at != nil && !isInt(at) {
- v.errf(at, join(path, "at_seconds"), "Field 'at_seconds' must be an integer")
- }
- if every != nil {
- if seconds, ok := intValue(every); !ok || seconds < 1 {
- v.errf(every, join(path, "every_seconds"),
- "Field 'every_seconds' must be a positive integer")
- }
- }
-
- if target := mapGet(n, "target"); target != nil {
- v.target(target, join(path, "target"))
- }
- v.incidentTypeFields(n, incidentType, path)
-}
-
-// incidentType reads and checks the `type` key shared by both incident paths.
-func (v *validator) incidentType(n *yaml.Node, path string) (string, bool) {
- typeNode := mapGet(n, "type")
- if typeNode == nil {
- v.errf(n, join(path, "type"), "Missing required field 'type'")
- return "", false
- }
- incidentType := scalarText(typeNode)
- if !validIncidentTypeNames.has(incidentType) {
- v.errf(typeNode, join(path, "type"),
- "Unknown incident type '%s'. Valid types: %s", incidentType, validIncidentTypeNames)
- return "", false
- }
- return incidentType, true
-}
-
-// incidentTypeFields checks the parameters each incident type requires: that the key is
-// present, and that its value is in range. Both checks apply wherever an incident
-// appears, standalone or inside a group.
-//
-// The two used to be split by a `strict` parameter that standalone incidents passed true
-// and group members passed false, so a group member could carry `delay_ms: -5` while the
-// identical standalone incident was rejected. That was not merely untidy: `rate: -5`
-// inside a group reached Producer.SetRate, which reads any value <= 0 as rate.Inf, so an
-// out-of-range value in a group silently unlimited the producer it targeted.
-func (v *validator) incidentTypeFields(n *yaml.Node, incidentType, path string) {
- switch incidentType {
- case IncidentStopBroker, IncidentStartBroker:
- broker := mapGet(n, "broker")
- if broker == nil {
- v.errf(n, join(path, "broker"),
- "Incident type '%s' requires 'broker' field", incidentType)
- } else if !Cluster.AllowsBroker(scalarText(broker)) {
- v.errf(broker, join(path, "broker"), "Invalid broker. Valid: %s", Cluster.brokerList())
- }
-
- case IncidentIncreaseConsumerDlay:
- delay := mapGet(n, "delay_ms")
- if delay == nil {
- v.errf(n, join(path, "delay_ms"),
- "Incident type 'increase_consumer_delay' requires 'delay_ms' field")
- } else {
- if ms, ok := intValue(delay); !ok || ms < 0 {
- v.errf(delay, join(path, "delay_ms"),
- "Field 'delay_ms' must be a non-negative integer")
- }
- }
-
- case IncidentChangeProducerRate:
- rate := mapGet(n, "rate")
- if rate == nil {
- v.errf(n, join(path, "rate"),
- "Incident type 'change_producer_rate' requires 'rate' field")
- } else {
- if r, ok := floatValue(rate); !ok || r < 0 {
- v.errf(rate, join(path, "rate"), "Field 'rate' must be a non-negative number")
- }
- }
-
- case IncidentPauseConsumer:
- duration := mapGet(n, "duration_seconds")
- if duration == nil {
- v.errf(n, join(path, "duration_seconds"),
- "Incident type 'pause_consumer' requires 'duration_seconds' field")
- } else {
- if seconds, ok := intValue(duration); !ok || seconds < 1 {
- v.errf(duration, join(path, "duration_seconds"),
- "Field 'duration_seconds' must be a positive integer")
- }
- }
- }
-}
-
-// target validates one `target:` block. Used for both consumer and producer targets;
-// producers have no group, but this does not distinguish, so a `group` on a producer
-// target is accepted here and then ignored at decode.
-func (v *validator) target(n *yaml.Node, path string) {
- if !isMapping(n) {
- v.errf(n, path, "Target must be an object/dict")
- return
- }
- v.knownKeys(n, path, "topic", "group", "group_id", "percentage", "count", "indices")
-
- if topic := mapGet(n, "topic"); topic != nil && !isString(topic) {
- v.errf(topic, join(path, "topic"), "Field 'topic' must be a string")
- }
- // `group_id` is validated alongside `group` because decode accepts both -- see
- // rawTarget.GroupID in decode.go.
- for _, key := range []string{"group", "group_id"} {
- if group := mapGet(n, key); group != nil && !isString(group) {
- v.errf(group, join(path, key), "Field '%s' must be a string", key)
- }
- }
-
- if pct := mapGet(n, "percentage"); pct != nil {
- if value, ok := intValue(pct); !ok || value < 1 || value > 100 {
- v.errf(pct, join(path, "percentage"),
- "Field 'percentage' must be an integer between 1 and 100")
- }
- }
- if count := mapGet(n, "count"); count != nil {
- if value, ok := intValue(count); !ok || value < 1 {
- v.errf(count, join(path, "count"), "Field 'count' must be a positive integer")
- }
- }
- if indices := mapGet(n, "indices"); indices != nil {
- if !isSequence(indices) {
- v.errf(indices, join(path, "indices"), "Field 'indices' must be a list")
- } else {
- for _, item := range seqItems(indices) {
- if value, ok := intValue(item); !ok || value < 0 {
- v.errf(indices, join(path, "indices"),
- "Field 'indices' must be a list of non-negative integers")
- break
- }
- }
- }
- }
-
- // The three selection keys are mutually exclusive.
- var set []string
- for _, key := range []string{"percentage", "count", "indices"} {
- if mapGet(n, key) != nil {
- set = append(set, key)
- }
- }
- if len(set) > 1 {
- v.errf(n, path, "Only one of percentage, count, indices can be set, got: %s",
- strings.Join(set, ", "))
- }
-}
-
-// incidentGroup validates a `group:` block.
-//
-// repeat and interval_seconds are REQUIRED here even though decode defaults them to 1
-// and 60 when missing; validation is stricter than decode and that is preserved.
-func (v *validator) incidentGroup(n *yaml.Node, path string) {
- if !isMapping(n) {
- v.errf(n, path, "Incident group must be an object/dict")
- return
- }
- v.knownKeys(n, path, "repeat", "interval_seconds", "incidents")
-
- switch repeat := mapGet(n, "repeat"); {
- case repeat == nil:
- v.errf(n, join(path, "repeat"), "Missing required field 'repeat'")
- default:
- if value, ok := intValue(repeat); !ok || value < 1 {
- v.errf(repeat, join(path, "repeat"), "Field 'repeat' must be a positive integer")
- }
- }
-
- intervalNode := mapGet(n, "interval_seconds")
- switch {
- case intervalNode == nil:
- v.errf(n, join(path, "interval_seconds"), "Missing required field 'interval_seconds'")
- default:
- if value, ok := intValue(intervalNode); !ok || value < 1 {
- v.errf(intervalNode, join(path, "interval_seconds"),
- "Field 'interval_seconds' must be a positive integer")
- }
- }
-
- incidents := mapGet(n, "incidents")
- switch {
- case incidents == nil:
- v.errf(n, join(path, "incidents"), "Missing required field 'incidents'")
- case !isSequence(incidents):
- v.errf(incidents, join(path, "incidents"), "Field 'incidents' must be a list")
- case len(seqItems(incidents)) == 0:
- v.errf(incidents, join(path, "incidents"), "Incident group must have at least one incident")
- default:
- for i, inc := range seqItems(incidents) {
- v.groupIncident(inc, index(join(path, "incidents"), i))
- }
- }
-
- // A member scheduled at or past the cycle length overlaps the next repetition --
- // warning only.
- if interval, ok := intValue(intervalNode); ok && isSequence(incidents) {
- for i, inc := range seqItems(incidents) {
- atNode := mapGet(inc, "at_seconds")
- if at, isInt := intValue(atNode); isInt && at >= interval {
- v.warnf(atNode, join(index(join(path, "incidents"), i), "at_seconds"),
- "at_seconds (%d) >= interval (%d), may overlap", at, interval)
- }
- }
- }
-}
-
-// groupIncident validates one member of a `group:` block's `incidents:` list. Differs
-// from a standalone incident in two ways: no schedule is required (a missing at_seconds
-// is a warning), and every_seconds is not checked at all. Type-specific field values are
-// checked exactly as they are outside a group.
-func (v *validator) groupIncident(n *yaml.Node, path string) {
- if !isMapping(n) {
- v.errf(n, path, "Incident must be an object/dict")
- return
- }
- v.knownKeys(n, path, incidentKeys...)
-
- incidentType, ok := v.incidentType(n, path)
- if !ok {
- return
- }
-
- at := mapGet(n, "at_seconds")
- if at == nil {
- v.warnf(n, path, "Group incidents should use 'at_seconds' (relative to cycle start)")
- } else if !isInt(at) {
- v.errf(at, join(path, "at_seconds"), "Field 'at_seconds' must be an integer")
- }
-
- if target := mapGet(n, "target"); target != nil {
- v.target(target, join(path, "target"))
- }
- v.incidentTypeFields(n, incidentType, path)
-}
diff --git a/internal/scenario/validate_field.go b/internal/scenario/validate_field.go
new file mode 100644
index 0000000..2c53e67
--- /dev/null
+++ b/internal/scenario/validate_field.go
@@ -0,0 +1,221 @@
+package scenario
+
+import (
+ "go.yaml.in/yaml/v3"
+)
+
+func (v *validator) fields(n *yaml.Node, path string) {
+ if !isSequence(n) {
+ v.errf(n, path, "fields must be a list")
+ return
+ }
+ for i, f := range seqItems(n) {
+ v.field(f, index(path, i), false)
+ }
+}
+
+// field validates one field definition, recursing into nested objects and array items.
+//
+// asItem distinguishes a named field from an array's `items:` schema, which differ in
+// two ways preserved verbatim: an array item needs no `name`, and an array item of type
+// faker is NOT checked for a `provider`, because the dispatch below skips fakerField
+// when asItem is set.
+//
+// A YAML anchor can make a field definition contain itself:
+//
+// fields:
+// - &f
+// name: a
+// type: array
+// items: *f
+//
+// Without a guard that recurses forever, appending another ".items" to the diagnostic
+// path on each pass until the process is killed. Nodes on the current recursion stack
+// are therefore tracked and re-entry is reported as an error. A finite tree, however
+// deeply nested, is unaffected: only an alias can revisit a node.
+func (v *validator) field(n *yaml.Node, path string, asItem bool) {
+ n = resolveNode(n)
+ if v.visiting[n] {
+ v.errf(n, path, "Field definition refers to itself through a YAML anchor")
+ return
+ }
+ if v.visiting == nil {
+ v.visiting = make(map[*yaml.Node]bool)
+ }
+ v.visiting[n] = true
+ defer delete(v.visiting, n)
+
+ if !isMapping(n) {
+ if asItem {
+ v.errf(n, path, "Array item must be an object/dict")
+ } else {
+ v.errf(n, path, "Field must be an object/dict")
+ }
+ return
+ }
+ v.knownKeys(n, path, "name", "type", "min", "max", "min_length", "max_length",
+ "cardinality", "values", "fields", "items", "min_items", "max_items",
+ "provider", "locale")
+
+ if !asItem {
+ switch name := mapGet(n, "name"); {
+ case name == nil:
+ v.errf(n, join(path, "name"), "Missing required field 'name'")
+ case !isString(name):
+ v.errf(name, join(path, "name"), "Field 'name' must be a string")
+ }
+ }
+
+ typeNode := mapGet(n, "type")
+ if typeNode == nil {
+ v.errf(n, join(path, "type"), "Missing required field 'type'")
+ return
+ }
+ if !isString(typeNode) {
+ v.errf(typeNode, join(path, "type"), "Field 'type' must be a string")
+ return
+ }
+ fieldType := typeNode.Value
+ if !ValidFieldTypes[fieldType] {
+ v.errf(typeNode, join(path, "type"),
+ "Unknown field type '%s'. Valid types: %s", fieldType, sortedFieldTypes)
+ return
+ }
+
+ switch fieldType {
+ case FieldString:
+ v.stringField(n, path)
+ case FieldInt:
+ v.numericRange(n, path)
+ v.cardinality(n, path)
+ case FieldFloat:
+ // No cardinality check for floats.
+ v.numericRange(n, path)
+ case FieldEnum:
+ v.enumField(n, path)
+ case FieldObject:
+ v.objectField(n, path)
+ case FieldArray:
+ v.arrayField(n, path)
+ case FieldFaker:
+ if !asItem {
+ v.fakerField(n, path)
+ }
+ }
+}
+
+// stringField validates the string-only constraints.
+func (v *validator) stringField(n *yaml.Node, path string) {
+ v.intAtLeast(n, path, "min_length", 0, "Field 'min_length' must be a non-negative integer")
+ v.intAtLeast(n, path, "max_length", 1, "Field 'max_length' must be a positive integer")
+ // The defaults here (0 and 100) are the validator's own; the field model has no
+ // length defaults at all.
+ v.pairing(n, path, "min_length", "max_length", 0, 100,
+ "min_length cannot be greater than max_length")
+ v.cardinality(n, path)
+}
+
+// cardinality validates the shared `cardinality:` key.
+func (v *validator) cardinality(n *yaml.Node, path string) {
+ v.intAtLeast(n, path, "cardinality", 1, "Field 'cardinality' must be a positive integer")
+}
+
+// numericRange validates min/max: they may be int or float, and are only compared when
+// both are present.
+func (v *validator) numericRange(n *yaml.Node, path string) {
+ minNode, maxNode := mapGet(n, "min"), mapGet(n, "max")
+ minOK, maxOK := true, true
+ if minNode != nil && !isNumber(minNode) {
+ v.errf(minNode, join(path, "min"), "Field 'min' must be a number")
+ minOK = false
+ }
+ if maxNode != nil && !isNumber(maxNode) {
+ v.errf(maxNode, join(path, "max"), "Field 'max' must be a number")
+ maxOK = false
+ }
+ if minNode == nil || maxNode == nil || !minOK || !maxOK {
+ return
+ }
+ minVal, _ := floatValue(minNode)
+ maxVal, _ := floatValue(maxNode)
+ if minVal > maxVal {
+ v.errf(minNode, path, "min cannot be greater than max")
+ }
+}
+
+// enumField validates an enum field's `values:` list.
+func (v *validator) enumField(n *yaml.Node, path string) {
+ values := mapGet(n, "values")
+ if values == nil {
+ v.errf(n, join(path, "values"), "Enum field requires 'values' list")
+ return
+ }
+ if !isSequence(values) {
+ v.errf(values, join(path, "values"), "Field 'values' must be a list")
+ return
+ }
+ items := seqItems(values)
+ if len(items) == 0 {
+ v.errf(values, join(path, "values"), "Enum must have at least one value")
+ }
+ for i, item := range items {
+ if !isString(item) {
+ v.errf(item, index(join(path, "values"), i), "Enum values must be strings")
+ }
+ }
+}
+
+// objectField validates an object field's nested `fields:` list.
+func (v *validator) objectField(n *yaml.Node, path string) {
+ fields := mapGet(n, "fields")
+ if fields == nil {
+ v.errf(n, join(path, "fields"), "Object field requires 'fields' list")
+ return
+ }
+ if !isSequence(fields) {
+ v.errf(fields, join(path, "fields"), "Field 'fields' must be a list")
+ return
+ }
+ items := seqItems(fields)
+ if len(items) == 0 {
+ v.errf(fields, join(path, "fields"), "Object must have at least one field")
+ }
+ // Nested object fields are full fields, so they do need a name.
+ for i, nested := range items {
+ v.field(nested, index(join(path, "fields"), i), false)
+ }
+}
+
+// arrayField validates an array field's `items:` schema and length bounds.
+func (v *validator) arrayField(n *yaml.Node, path string) {
+ items := mapGet(n, "items")
+ if items == nil {
+ v.errf(n, join(path, "items"), "Array field requires 'items' schema")
+ return
+ }
+ if !isMapping(items) {
+ v.errf(items, join(path, "items"), "Field 'items' must be an object/dict")
+ return
+ }
+ v.intAtLeast(n, path, "min_items", 0, "Field 'min_items' must be a non-negative integer")
+ v.intAtLeast(n, path, "max_items", 1, "Field 'max_items' must be a positive integer")
+ v.pairing(n, path, "min_items", "max_items", defaultMinItems, defaultMaxItems,
+ "min_items cannot be greater than max_items")
+ v.field(items, join(path, "items"), true)
+}
+
+// fakerField validates a faker field's `provider:`/`locale:` keys.
+func (v *validator) fakerField(n *yaml.Node, path string) {
+ provider := mapGet(n, "provider")
+ if provider == nil {
+ v.errf(n, join(path, "provider"), "Faker field requires 'provider'")
+ return
+ }
+ if !isString(provider) {
+ v.errf(provider, join(path, "provider"), "Field 'provider' must be a string")
+ return
+ }
+ if locale := mapGet(n, "locale"); locale != nil && !isString(locale) {
+ v.errf(locale, join(path, "locale"), "Field 'locale' must be a string")
+ }
+}
diff --git a/internal/scenario/validate_flow.go b/internal/scenario/validate_flow.go
new file mode 100644
index 0000000..9de41eb
--- /dev/null
+++ b/internal/scenario/validate_flow.go
@@ -0,0 +1,145 @@
+package scenario
+
+import (
+ "go.yaml.in/yaml/v3"
+)
+
+func (v *validator) flows(n *yaml.Node, path string) {
+ if !isSequence(n) {
+ v.errf(n, path, "Field 'flows' must be a list")
+ return
+ }
+ for i, f := range seqItems(n) {
+ v.flow(f, index(path, i))
+ }
+}
+
+// flow validates one entry of `flows:`.
+func (v *validator) flow(n *yaml.Node, path string) {
+ if !isMapping(n) {
+ v.errf(n, path, "Flow must be an object/dict")
+ return
+ }
+ v.knownKeys(n, path, "name", "rate", "steps", "correlation")
+
+ switch name := mapGet(n, "name"); {
+ case name == nil:
+ v.errf(n, join(path, "name"), "Missing required field 'name'")
+ case !isString(name):
+ v.errf(name, join(path, "name"), "Field 'name' must be a string")
+ }
+
+ if rate := mapGet(n, "rate"); rate != nil {
+ if r, ok := floatValue(rate); !ok || r <= 0 {
+ v.errf(rate, join(path, "rate"), "Field 'rate' must be a positive number")
+ }
+ }
+ if corr := mapGet(n, "correlation"); corr != nil {
+ v.correlation(corr, join(path, "correlation"))
+ }
+
+ steps := mapGet(n, "steps")
+ if steps == nil {
+ v.errf(n, join(path, "steps"), "Missing required field 'steps'")
+ return
+ }
+ if !isSequence(steps) {
+ v.errf(steps, join(path, "steps"), "Field 'steps' must be a list")
+ return
+ }
+ items := seqItems(steps)
+ // A one-step flow is legal but pointless -- warning, not error.
+ if len(items) < 2 {
+ v.warnf(steps, join(path, "steps"),
+ "Flow has fewer than 2 steps - consider using regular topics instead")
+ }
+ for i, step := range items {
+ v.flowStep(step, index(join(path, "steps"), i), i == 0)
+ }
+}
+
+// correlation validates a `correlation:` block. field_ref without a field name is the
+// one hard error here.
+func (v *validator) correlation(n *yaml.Node, path string) {
+ if !isMapping(n) {
+ v.errf(n, path, "correlation must be an object/dict")
+ return
+ }
+ v.knownKeys(n, path, "type", "field")
+
+ corrType := defaultCorrelationType
+ typeNode := mapGet(n, "type")
+ if typeNode != nil {
+ corrType = scalarText(typeNode)
+ }
+ if !validCorrelationTypes.has(corrType) {
+ v.errf(cmpNode(typeNode, n), join(path, "type"),
+ "Invalid correlation type '%s'. Valid types: %s", corrType, validCorrelationTypes)
+ }
+ if corrType == CorrelationFieldRef {
+ switch fieldNode := mapGet(n, "field"); {
+ case fieldNode == nil:
+ v.errf(n, join(path, "field"),
+ "Correlation type 'field_ref' requires 'field' to be specified")
+ case !isString(fieldNode):
+ v.errf(fieldNode, join(path, "field"), "Field 'field' must be a string")
+ }
+ }
+}
+
+// flowStep validates one entry of a flow's `steps:` list.
+func (v *validator) flowStep(n *yaml.Node, path string, isFirst bool) {
+ if !isMapping(n) {
+ v.errf(n, path, "Step must be an object/dict")
+ return
+ }
+ v.knownKeys(n, path, "topic", "event_type", "delay_ms", "fields", "consumers")
+
+ switch topic := mapGet(n, "topic"); {
+ case topic == nil:
+ v.errf(n, join(path, "topic"), "Missing required field 'topic'")
+ case !isString(topic):
+ v.errf(topic, join(path, "topic"), "Field 'topic' must be a string")
+ }
+ switch event := mapGet(n, "event_type"); {
+ case event == nil:
+ v.errf(n, join(path, "event_type"), "Missing required field 'event_type'")
+ case !isString(event):
+ v.errf(event, join(path, "event_type"), "Field 'event_type' must be a string")
+ }
+
+ if delay := mapGet(n, "delay_ms"); delay != nil {
+ if ms, ok := intValue(delay); !ok || ms < 0 {
+ v.errf(delay, join(path, "delay_ms"), "Field 'delay_ms' must be a non-negative integer")
+ }
+ // The range check above and the first-step warning below are independent
+ // checks against the raw value, not chained as an else-branch: a first-step
+ // `delay_ms: 1.5` produces BOTH the range error and this warning. Reading the
+ // value as a float here (rather than only as an int) is what surfaces the
+ // warning even when the range check already failed. A non-numeric delay_ms
+ // fails the isNum check below, so it produces the range error alone.
+ if value, isNum := floatValue(delay); isFirst && isNum && value > 0 {
+ v.warnf(delay, join(path, "delay_ms"),
+ "First step has delay_ms - delay applies before flow starts")
+ }
+ }
+
+ if fields := mapGet(n, "fields"); fields != nil {
+ v.fields(fields, join(path, "fields"))
+ }
+ if consumers := mapGet(n, "consumers"); consumers != nil {
+ v.stepConsumers(consumers, join(path, "consumers"))
+ }
+}
+
+// stepConsumers validates a step's `consumers:` block.
+func (v *validator) stepConsumers(n *yaml.Node, path string) {
+ if !isMapping(n) {
+ v.errf(n, path, "consumers must be an object/dict")
+ return
+ }
+ v.knownKeys(n, path, "groups", "per_group", "delay_ms")
+ v.intAtLeast(n, path, "groups", 1, "Field 'groups' must be a positive integer")
+ v.intAtLeast(n, path, "per_group", 1, "Field 'per_group' must be a positive integer")
+ v.intAtLeast(n, path, "delay_ms", 0, "Field 'delay_ms' must be a non-negative integer")
+}
diff --git a/internal/scenario/validate_incident.go b/internal/scenario/validate_incident.go
new file mode 100644
index 0000000..b6121cc
--- /dev/null
+++ b/internal/scenario/validate_incident.go
@@ -0,0 +1,272 @@
+package scenario
+
+import (
+ "strings"
+
+ "go.yaml.in/yaml/v3"
+)
+
+// incidentKeys is the union of every key any incident type reads, plus `group`.
+var incidentKeys = []string{
+ "type", "group", "at_seconds", "every_seconds", "initial_delay_seconds",
+ "target", "broker", "duration_seconds", "delay_ms", "rate",
+}
+
+// incident validates one entry of the top-level `incidents:` list, which is either a
+// standalone incident or a group wrapper.
+func (v *validator) incident(n *yaml.Node, path string) {
+ if !isMapping(n) {
+ v.errf(n, path, "Incident must be an object/dict")
+ return
+ }
+ // A `group` key makes the whole entry a group and nothing else on it is read.
+ if group := mapGet(n, "group"); group != nil {
+ v.incidentGroup(group, join(path, "group"))
+ return
+ }
+ v.knownKeys(n, path, incidentKeys...)
+
+ incidentType, ok := v.incidentType(n, path)
+ if !ok {
+ return
+ }
+
+ // Standalone incidents need a schedule; group members do not.
+ at, every := mapGet(n, "at_seconds"), mapGet(n, "every_seconds")
+ if at == nil && every == nil {
+ v.errf(n, path, "Incident must have either 'at_seconds' or 'every_seconds'")
+ }
+ if at != nil && !isInt(at) {
+ v.errf(at, join(path, "at_seconds"), "Field 'at_seconds' must be an integer")
+ }
+ if every != nil {
+ if seconds, ok := intValue(every); !ok || seconds < 1 {
+ v.errf(every, join(path, "every_seconds"),
+ "Field 'every_seconds' must be a positive integer")
+ }
+ }
+
+ if target := mapGet(n, "target"); target != nil {
+ v.target(target, join(path, "target"))
+ }
+ v.incidentTypeFields(n, incidentType, path)
+}
+
+// incidentType reads and checks the `type` key shared by both incident paths.
+func (v *validator) incidentType(n *yaml.Node, path string) (string, bool) {
+ typeNode := mapGet(n, "type")
+ if typeNode == nil {
+ v.errf(n, join(path, "type"), "Missing required field 'type'")
+ return "", false
+ }
+ incidentType := scalarText(typeNode)
+ if !validIncidentTypeNames.has(incidentType) {
+ v.errf(typeNode, join(path, "type"),
+ "Unknown incident type '%s'. Valid types: %s", incidentType, validIncidentTypeNames)
+ return "", false
+ }
+ return incidentType, true
+}
+
+// incidentTypeFields checks the parameters each incident type requires: that the key is
+// present, and that its value is in range. Both checks apply wherever an incident
+// appears, standalone or inside a group.
+//
+// The two used to be split by a `strict` parameter that standalone incidents passed true
+// and group members passed false, so a group member could carry `delay_ms: -5` while the
+// identical standalone incident was rejected. That was not merely untidy: `rate: -5`
+// inside a group reached Producer.SetRate, which reads any value <= 0 as rate.Inf, so an
+// out-of-range value in a group silently unlimited the producer it targeted.
+func (v *validator) incidentTypeFields(n *yaml.Node, incidentType, path string) {
+ switch incidentType {
+ case IncidentStopBroker, IncidentStartBroker:
+ broker := mapGet(n, "broker")
+ if broker == nil {
+ v.errf(n, join(path, "broker"),
+ "Incident type '%s' requires 'broker' field", incidentType)
+ } else if !Cluster.AllowsBroker(scalarText(broker)) {
+ v.errf(broker, join(path, "broker"), "Invalid broker. Valid: %s", Cluster.brokerList())
+ }
+
+ case IncidentIncreaseConsumerDelay:
+ delay := mapGet(n, "delay_ms")
+ if delay == nil {
+ v.errf(n, join(path, "delay_ms"),
+ "Incident type 'increase_consumer_delay' requires 'delay_ms' field")
+ } else {
+ if ms, ok := intValue(delay); !ok || ms < 0 {
+ v.errf(delay, join(path, "delay_ms"),
+ "Field 'delay_ms' must be a non-negative integer")
+ }
+ }
+
+ case IncidentChangeProducerRate:
+ rate := mapGet(n, "rate")
+ if rate == nil {
+ v.errf(n, join(path, "rate"),
+ "Incident type 'change_producer_rate' requires 'rate' field")
+ } else {
+ if r, ok := floatValue(rate); !ok || r < 0 {
+ v.errf(rate, join(path, "rate"), "Field 'rate' must be a non-negative number")
+ }
+ }
+
+ case IncidentPauseConsumer:
+ duration := mapGet(n, "duration_seconds")
+ if duration == nil {
+ v.errf(n, join(path, "duration_seconds"),
+ "Incident type 'pause_consumer' requires 'duration_seconds' field")
+ } else {
+ if seconds, ok := intValue(duration); !ok || seconds < 1 {
+ v.errf(duration, join(path, "duration_seconds"),
+ "Field 'duration_seconds' must be a positive integer")
+ }
+ }
+ }
+}
+
+// target validates one `target:` block. Used for both consumer and producer targets;
+// producers have no group, but this does not distinguish, so a `group` on a producer
+// target is accepted here and then ignored at decode.
+func (v *validator) target(n *yaml.Node, path string) {
+ if !isMapping(n) {
+ v.errf(n, path, "Target must be an object/dict")
+ return
+ }
+ v.knownKeys(n, path, "topic", "group", "group_id", "percentage", "count", "indices")
+
+ if topic := mapGet(n, "topic"); topic != nil && !isString(topic) {
+ v.errf(topic, join(path, "topic"), "Field 'topic' must be a string")
+ }
+ // `group_id` is validated alongside `group` because decode accepts both -- see
+ // rawTarget.GroupID in decode.go.
+ for _, key := range []string{"group", "group_id"} {
+ if group := mapGet(n, key); group != nil && !isString(group) {
+ v.errf(group, join(path, key), "Field '%s' must be a string", key)
+ }
+ }
+
+ if pct := mapGet(n, "percentage"); pct != nil {
+ if value, ok := intValue(pct); !ok || value < 1 || value > 100 {
+ v.errf(pct, join(path, "percentage"),
+ "Field 'percentage' must be an integer between 1 and 100")
+ }
+ }
+ if count := mapGet(n, "count"); count != nil {
+ if value, ok := intValue(count); !ok || value < 1 {
+ v.errf(count, join(path, "count"), "Field 'count' must be a positive integer")
+ }
+ }
+ if indices := mapGet(n, "indices"); indices != nil {
+ if !isSequence(indices) {
+ v.errf(indices, join(path, "indices"), "Field 'indices' must be a list")
+ } else {
+ for _, item := range seqItems(indices) {
+ if value, ok := intValue(item); !ok || value < 0 {
+ v.errf(indices, join(path, "indices"),
+ "Field 'indices' must be a list of non-negative integers")
+ break
+ }
+ }
+ }
+ }
+
+ // The three selection keys are mutually exclusive.
+ var set []string
+ for _, key := range []string{"percentage", "count", "indices"} {
+ if mapGet(n, key) != nil {
+ set = append(set, key)
+ }
+ }
+ if len(set) > 1 {
+ v.errf(n, path, "Only one of percentage, count, indices can be set, got: %s",
+ strings.Join(set, ", "))
+ }
+}
+
+// incidentGroup validates a `group:` block.
+//
+// repeat and interval_seconds are REQUIRED here even though decode defaults them to 1
+// and 60 when missing; validation is stricter than decode and that is preserved.
+func (v *validator) incidentGroup(n *yaml.Node, path string) {
+ if !isMapping(n) {
+ v.errf(n, path, "Incident group must be an object/dict")
+ return
+ }
+ v.knownKeys(n, path, "repeat", "interval_seconds", "incidents")
+
+ switch repeat := mapGet(n, "repeat"); {
+ case repeat == nil:
+ v.errf(n, join(path, "repeat"), "Missing required field 'repeat'")
+ default:
+ if value, ok := intValue(repeat); !ok || value < 1 {
+ v.errf(repeat, join(path, "repeat"), "Field 'repeat' must be a positive integer")
+ }
+ }
+
+ intervalNode := mapGet(n, "interval_seconds")
+ switch {
+ case intervalNode == nil:
+ v.errf(n, join(path, "interval_seconds"), "Missing required field 'interval_seconds'")
+ default:
+ if value, ok := intValue(intervalNode); !ok || value < 1 {
+ v.errf(intervalNode, join(path, "interval_seconds"),
+ "Field 'interval_seconds' must be a positive integer")
+ }
+ }
+
+ incidents := mapGet(n, "incidents")
+ switch {
+ case incidents == nil:
+ v.errf(n, join(path, "incidents"), "Missing required field 'incidents'")
+ case !isSequence(incidents):
+ v.errf(incidents, join(path, "incidents"), "Field 'incidents' must be a list")
+ case len(seqItems(incidents)) == 0:
+ v.errf(incidents, join(path, "incidents"), "Incident group must have at least one incident")
+ default:
+ for i, inc := range seqItems(incidents) {
+ v.groupIncident(inc, index(join(path, "incidents"), i))
+ }
+ }
+
+ // A member scheduled at or past the cycle length overlaps the next repetition --
+ // warning only.
+ if interval, ok := intValue(intervalNode); ok && isSequence(incidents) {
+ for i, inc := range seqItems(incidents) {
+ atNode := mapGet(inc, "at_seconds")
+ if at, isInt := intValue(atNode); isInt && at >= interval {
+ v.warnf(atNode, join(index(join(path, "incidents"), i), "at_seconds"),
+ "at_seconds (%d) >= interval (%d), may overlap", at, interval)
+ }
+ }
+ }
+}
+
+// groupIncident validates one member of a `group:` block's `incidents:` list. Differs
+// from a standalone incident in two ways: no schedule is required (a missing at_seconds
+// is a warning), and every_seconds is not checked at all. Type-specific field values are
+// checked exactly as they are outside a group.
+func (v *validator) groupIncident(n *yaml.Node, path string) {
+ if !isMapping(n) {
+ v.errf(n, path, "Incident must be an object/dict")
+ return
+ }
+ v.knownKeys(n, path, incidentKeys...)
+
+ incidentType, ok := v.incidentType(n, path)
+ if !ok {
+ return
+ }
+
+ at := mapGet(n, "at_seconds")
+ if at == nil {
+ v.warnf(n, path, "Group incidents should use 'at_seconds' (relative to cycle start)")
+ } else if !isInt(at) {
+ v.errf(at, join(path, "at_seconds"), "Field 'at_seconds' must be an integer")
+ }
+
+ if target := mapGet(n, "target"); target != nil {
+ v.target(target, join(path, "target"))
+ }
+ v.incidentTypeFields(n, incidentType, path)
+}
diff --git a/internal/scenario/validate_topic.go b/internal/scenario/validate_topic.go
new file mode 100644
index 0000000..2c8d218
--- /dev/null
+++ b/internal/scenario/validate_topic.go
@@ -0,0 +1,321 @@
+package scenario
+
+import (
+ "fmt"
+ "strings"
+
+ "go.yaml.in/yaml/v3"
+)
+
+// topics validates the topic list and emits the schemaless-mode warning.
+//
+// The warning names the data_format of the LAST avro/protobuf topic seen, since the
+// scan reassigns schemaFormatName on every matching topic in the loop.
+func (v *validator) topics(n *yaml.Node, hasSchemaRegistry bool) {
+ if !isSequence(n) {
+ v.errf(n, "topics", "Field 'topics' must be a list")
+ return
+ }
+ schemaFormatName := ""
+ var lastFormatNode *yaml.Node
+ for i, topic := range seqItems(n) {
+ path := index("topics", i)
+ v.topic(topic, path)
+ format := mapGet(mapGet(topic, "message_schema"), "data_format")
+ if text := scalarText(format); text == "avro" || text == "protobuf" {
+ schemaFormatName = text
+ lastFormatNode = format
+ }
+ }
+ if schemaFormatName != "" && !hasSchemaRegistry {
+ v.warnf(lastFormatNode, "schema_registry",
+ "Using %s without Schema Registry (schemaless mode)", title(schemaFormatName))
+ }
+}
+
+// title upper-cases the first letter of a single-word format name ("avro" -> "Avro",
+// "protobuf" -> "Protobuf").
+func title(s string) string {
+ if s == "" {
+ return s
+ }
+ return strings.ToUpper(s[:1]) + s[1:]
+}
+
+// topic validates one entry of `topics:`.
+func (v *validator) topic(n *yaml.Node, path string) {
+ if !isMapping(n) {
+ v.errf(n, path, "Topic must be an object/dict")
+ return
+ }
+ v.knownKeys(n, path,
+ "name", "partitions", "replication_factor", "num_producers", "num_consumer_groups",
+ "consumers_per_group", "producer_rate", "consumer_delay_ms", "message_schema",
+ "producer_config", "consumer_config", "schema_provider", "subject_name")
+
+ switch name := mapGet(n, "name"); {
+ case name == nil:
+ v.errf(n, join(path, "name"), "Missing required field 'name'")
+ case !isString(name):
+ v.errf(name, join(path, "name"), "Field 'name' must be a string")
+ }
+
+ // partitions: the >100 case is a warning, not an error.
+ if p := mapGet(n, "partitions"); p != nil {
+ if count, ok := intValue(p); !ok || count < 1 {
+ v.errf(p, join(path, "partitions"), "Field 'partitions' must be a positive integer")
+ } else if count > 100 {
+ v.warnf(p, join(path, "partitions"),
+ "High partition count (%d) may impact performance", count)
+ }
+ }
+
+ // replication_factor: the upper bound is a cluster assumption (see Cluster).
+ if rf := mapGet(n, "replication_factor"); rf != nil {
+ if factor, ok := intValue(rf); !ok || factor < 1 {
+ v.errf(rf, join(path, "replication_factor"),
+ "Field 'replication_factor' must be a positive integer")
+ } else if factor > Cluster.MaxReplicationFactor() {
+ v.errf(rf, join(path, "replication_factor"),
+ "Replication factor cannot exceed %d (cluster has %d brokers)",
+ Cluster.MaxReplicationFactor(), len(Cluster.Brokers))
+ }
+ }
+
+ // num_producers is non-negative, unlike the other counts: zero producers is a
+ // legitimate consume-only topic.
+ v.intAtLeast(n, path, "num_producers", 0, "Field 'num_producers' must be a non-negative integer")
+ v.intAtLeast(n, path, "num_consumer_groups", 1, "Field 'num_consumer_groups' must be a positive integer")
+ v.intAtLeast(n, path, "consumers_per_group", 1, "Field 'consumers_per_group' must be a positive integer")
+
+ if rate := mapGet(n, "producer_rate"); rate != nil {
+ if r, ok := floatValue(rate); !ok || r <= 0 {
+ v.errf(rate, join(path, "producer_rate"), "Field 'producer_rate' must be a positive number")
+ }
+ }
+ v.intAtLeast(n, path, "consumer_delay_ms", 0, "Field 'consumer_delay_ms' must be a non-negative integer")
+
+ // schema_provider is read before message_schema because it changes whether fields
+ // are required or forbidden.
+ providerNode := mapGet(n, "schema_provider")
+ provider := defaultSchemaProvider
+ if providerNode != nil {
+ provider = scalarText(providerNode)
+ }
+
+ if ms := mapGet(n, "message_schema"); ms != nil {
+ v.messageSchema(ms, join(path, "message_schema"), provider)
+ }
+ if pc := mapGet(n, "producer_config"); pc != nil {
+ v.producerConfig(pc, join(path, "producer_config"))
+ }
+ if cc := mapGet(n, "consumer_config"); cc != nil {
+ v.consumerConfig(cc, join(path, "consumer_config"))
+ }
+
+ if !validSchemaProviders.has(provider) {
+ v.errf(providerNode, join(path, "schema_provider"),
+ "Invalid schema_provider '%s'. Valid values: %s", provider, validSchemaProviders)
+ }
+
+ // registry provider: subject_name required, inline fields forbidden.
+ if provider == "registry" {
+ switch subject := mapGet(n, "subject_name"); {
+ case subject == nil:
+ v.errf(n, join(path, "subject_name"),
+ "Field 'subject_name' is required when schema_provider is 'registry'")
+ case !isString(subject):
+ v.errf(subject, join(path, "subject_name"), "Field 'subject_name' must be a string")
+ }
+ if fields := mapGet(mapGet(n, "message_schema"), "fields"); fields != nil && len(seqItems(fields)) > 0 {
+ v.errf(fields, path,
+ "Cannot define 'message_schema.fields' when schema_provider is 'registry' "+
+ "(schema will be fetched from Schema Registry)")
+ }
+ }
+}
+
+// intAtLeast is the shape shared by the "must be a (non-)negative integer" checks: the
+// key is optional, but when present it must be an int no smaller than lo.
+func (v *validator) intAtLeast(n *yaml.Node, path, key string, lo int, message string) {
+ node := mapGet(n, key)
+ if node == nil {
+ return
+ }
+ if value, ok := intValue(node); !ok || value < lo {
+ v.errf(node, join(path, key), "%s", message)
+ }
+}
+
+// messageSchema validates one `message_schema:` block.
+func (v *validator) messageSchema(n *yaml.Node, path, provider string) {
+ if !isMapping(n) {
+ v.errf(n, path, "message_schema must be an object/dict")
+ return
+ }
+ v.knownKeys(n, path, "key_distribution", "key_cardinality", "min_size_bytes",
+ "max_size_bytes", "data_format", "fields")
+
+ if kd := mapGet(n, "key_distribution"); kd != nil {
+ if text := scalarText(kd); !validKeyDistributions.has(text) {
+ v.errf(kd, join(path, "key_distribution"),
+ "Invalid key_distribution '%s'. Valid values: %s", text, validKeyDistributions)
+ }
+ }
+ v.intAtLeast(n, path, "key_cardinality", 1, "Field 'key_cardinality' must be a positive integer")
+
+ if df := mapGet(n, "data_format"); df != nil {
+ text := scalarText(df)
+ if !validDataFormats.has(text) {
+ v.errf(df, join(path, "data_format"),
+ "Invalid data_format '%s'. Valid values: %s", text, validDataFormats)
+ }
+ // Binary formats need a schema to encode against. The registry provider
+ // supplies one at runtime, so the requirement only applies inline.
+ fields := mapGet(n, "fields")
+ hasFields := fields != nil && len(seqItems(fields)) > 0
+ if provider == "inline" && (text == "avro" || text == "protobuf") && !hasFields {
+ v.errf(df, join(path, "fields"),
+ "data_format '%s' requires 'fields' to be defined "+
+ "(or use schema_provider: registry to fetch from Schema Registry)", text)
+ }
+ }
+
+ v.intAtLeast(n, path, "min_size_bytes", 1, "Field 'min_size_bytes' must be a positive integer")
+ v.intAtLeast(n, path, "max_size_bytes", 1, "Field 'max_size_bytes' must be a positive integer")
+ // The pairing is checked against the defaults when a bound is omitted, so setting
+ // only min_size_bytes: 900 is an error against the default max of 500.
+ v.pairing(n, path, "min_size_bytes", "max_size_bytes", defaultMinSizeBytes, defaultMaxSizeBytes,
+ "min_size_bytes cannot be greater than max_size_bytes")
+
+ if fields := mapGet(n, "fields"); fields != nil {
+ v.fields(fields, join(path, "fields"))
+ }
+}
+
+// pairing reproduces the four "min cannot be greater than max" checks, each of which
+// falls back to the model default for an omitted bound and skips entirely when either
+// present value is not an integer.
+func (v *validator) pairing(n *yaml.Node, path, minKey, maxKey string, minDefault, maxDefault int, message string) {
+ minNode, maxNode := mapGet(n, minKey), mapGet(n, maxKey)
+ minVal, maxVal := minDefault, maxDefault
+ if minNode != nil {
+ value, ok := intValue(minNode)
+ if !ok {
+ return
+ }
+ minVal = value
+ }
+ if maxNode != nil {
+ value, ok := intValue(maxNode)
+ if !ok {
+ return
+ }
+ maxVal = value
+ }
+ if minVal > maxVal {
+ v.errf(cmpNode(minNode, n), path, "%s", message)
+ }
+}
+
+// cmpNode picks the most specific node available to hang a pairing error on.
+func cmpNode(preferred, fallback *yaml.Node) *yaml.Node {
+ if preferred != nil {
+ return preferred
+ }
+ return fallback
+}
+
+// schemaRegistry validates a top-level `schema_registry:` block.
+func (v *validator) schemaRegistry(n *yaml.Node, path string) {
+ if !isMapping(n) {
+ v.errf(n, path, "schema_registry must be an object/dict")
+ return
+ }
+ v.knownKeys(n, path, "url")
+ switch url := mapGet(n, "url"); {
+ case url == nil:
+ v.errf(n, join(path, "url"), "Missing required field 'url'")
+ case !isString(url):
+ v.errf(url, join(path, "url"), "Field 'url' must be a string")
+ case !strings.HasPrefix(url.Value, "http://") && !strings.HasPrefix(url.Value, "https://"):
+ v.errf(url, join(path, "url"), "Field 'url' must be a valid HTTP(S) URL")
+ }
+}
+
+// producerConfig validates one `producer_config:` block.
+func (v *validator) producerConfig(n *yaml.Node, path string) {
+ if !isMapping(n) {
+ v.errf(n, path, "producer_config must be an object/dict")
+ return
+ }
+ v.knownKeys(n, path, "batch_size", "linger_ms", "acks", "compression_type", "duplicate_rate")
+
+ v.intAtLeast(n, path, "batch_size", 0, "Field 'batch_size' must be a non-negative integer")
+ v.intAtLeast(n, path, "linger_ms", 0, "Field 'linger_ms' must be a non-negative integer")
+
+ // acks is compared as a string, so both `acks: 1` and `acks: "1"` are accepted.
+ if acks := mapGet(n, "acks"); acks != nil {
+ text := scalarText(acks)
+ if !validAcks.has(text) {
+ v.errf(acks, join(path, "acks"), "Invalid acks '%s'. Valid values: %s", text, validAcks)
+ }
+ }
+ if ct := mapGet(n, "compression_type"); ct != nil {
+ if text := scalarText(ct); !validCompressionTypes.has(text) {
+ v.errf(ct, join(path, "compression_type"),
+ "Invalid compression_type '%s'. Valid values: %s", text, validCompressionTypes)
+ }
+ }
+ v.rate01(n, path, "duplicate_rate",
+ "Field 'duplicate_rate' must be a number between 0.0 and 1.0",
+ "High duplicate rate (%s) will produce many duplicate messages")
+}
+
+// consumerConfig validates one `consumer_config:` block.
+func (v *validator) consumerConfig(n *yaml.Node, path string) {
+ if !isMapping(n) {
+ v.errf(n, path, "consumer_config must be an object/dict")
+ return
+ }
+ v.knownKeys(n, path, "failure_rate", "commit_failure_rate", "on_failure", "max_retries")
+
+ v.rate01(n, path, "failure_rate",
+ "Field 'failure_rate' must be a number between 0.0 and 1.0",
+ "High failure rate (%s) may cause significant message loss")
+ v.rate01(n, path, "commit_failure_rate",
+ "Field 'commit_failure_rate' must be a number between 0.0 and 1.0",
+ "High commit failure rate (%s) may cause significant reprocessing")
+
+ if of := mapGet(n, "on_failure"); of != nil {
+ text := scalarText(of)
+ if !validOnFailureActions.has(text) {
+ v.errf(of, join(path, "on_failure"),
+ "Invalid on_failure '%s'. Valid values: %s", text, validOnFailureActions)
+ } else if text == "dlq" {
+ v.warnf(of, join(path, "on_failure"),
+ "DLQ mode enabled - ensure DLQ topics exist or are auto-created")
+ }
+ }
+ v.intAtLeast(n, path, "max_retries", 0, "Field 'max_retries' must be a non-negative integer")
+}
+
+// rate01 is the shape shared by the three [0,1] probability keys: out of range is an
+// error, and anything above 0.5 is a warning rendered as a percentage.
+func (v *validator) rate01(n *yaml.Node, path, key, errMessage, warnFormat string) {
+ node := mapGet(n, key)
+ if node == nil {
+ return
+ }
+ rate, ok := floatValue(node)
+ if !ok || rate < 0 || rate > 1 {
+ v.errf(node, join(path, key), "%s", errMessage)
+ return
+ }
+ if rate > 0.5 {
+ v.warnf(node, join(path, key), warnFormat, percent(rate))
+ }
+}
+
+// percent renders a rate as a whole-number percentage, e.g. 0.75 -> "75%".
+func percent(rate float64) string { return fmt.Sprintf("%.0f%%", rate*100) }
diff --git a/internal/tui/render.go b/internal/tui/render.go
index 8920245..ecfe59e 100644
--- a/internal/tui/render.go
+++ b/internal/tui/render.go
@@ -52,6 +52,23 @@ const (
// titles compact, buying the name column room it otherwise loses whole names to.
const narrowWidth = 96
+// Height budget. The frame lines are chrome that costs the same at any height; the
+// floors are the terminal heights below which an optional piece is dropped outright.
+const (
+ // fixedChromeLines is the header, the totals bar and the quit hint.
+ fixedChromeLines = 3
+ // tableFrameLines is a bordered table's frame: top border, header, header rule,
+ // bottom border.
+ tableFrameLines = 4
+ // minTableRows is how many body rows the tables keep before events start giving
+ // up lines.
+ minTableRows = 4
+
+ minRuleHeight = 16
+ minFlowHeight = 13
+ minIssuesHeight = 12
+)
+
// render draws the frame top-down: header, topic table, optional flow table, rule, totals,
// issues, events, quit hint. An unknown terminal size falls back to 100x40, the same
// default New starts at, so every frame before the first WindowSizeMsg renders at that
@@ -71,14 +88,12 @@ func (m model) render() string {
// Height budget: fixed chrome first (header, totals, quit hint, optional rule and
// issues line), then remaining space splits between the topic table, flow table (capped
// at a third) and events, which give up lines one by one first since losing an old event
- // beats losing sight of a topic. The recurring 4 is a bordered table's frame -- top
- // border, header, header rule, bottom border -- and the floor is an 8-line frame
- // (header, one-row table, totals, hint); below that the layout clips rather than
- // contorts.
+ // beats losing sight of a topic. The floor is an 8-line frame (header, one-row table,
+ // totals, hint); below that the layout clips rather than contorts.
issues := m.issuesLine(w)
- showRule := h >= 16
- showIssues := issues != "" && h >= 12
- fixed := 3
+ showRule := h >= minRuleHeight
+ showIssues := issues != "" && h >= minIssuesHeight
+ fixed := fixedChromeLines
if showRule {
fixed++
}
@@ -90,16 +105,16 @@ func (m model) render() string {
if len(s.Events) > 0 {
eventsWant = min(6, len(s.Events))
}
- showFlows := len(s.Flows) > 0 && h >= 13
+ showFlows := len(s.Flows) > 0 && h >= minFlowHeight
flowFrame := 0
if showFlows {
- flowFrame = 4
+ flowFrame = tableFrameLines
}
- avail := h - fixed - eventsHeight(eventsWant) - 4 - flowFrame
- for avail < 4 && eventsWant > 0 {
+ avail := h - fixed - eventsHeight(eventsWant) - tableFrameLines - flowFrame
+ for avail < minTableRows && eventsWant > 0 {
eventsWant--
- avail = h - fixed - eventsHeight(eventsWant) - 4 - flowFrame
+ avail = h - fixed - eventsHeight(eventsWant) - tableFrameLines - flowFrame
}
flowBudget := 0
if showFlows {
@@ -472,16 +487,7 @@ func (m model) topicTable(w, budget int) string {
}
}
- // Name-column width: whatever the numeric block leaves behind, within its bounds.
- // If even the minimum does not fit, retry with compact padding before letting the
- // table clamp -- a clamped table shrinks columns of its own choosing.
- nameW := firstColWidth(w, colWidths(specs, allCells), pad)
- if nameW < minNameWidth && pad > 2 {
- pad = 2
- nameW = firstColWidth(w, colWidths(specs, allCells), pad)
- }
- nameW = max(min(nameW, maxNameWidth), minNameWidth)
- tw := min(w, nameW+pad+2+sumPlus(colWidths(specs, allCells), pad))
+ nameW, tw, pad := solveWidths(w, specs, allCells, pad)
headers := make([]string, 0, len(specs)+1)
headers = append(headers, padHeader("TOPIC", nameW))
@@ -505,6 +511,23 @@ func (m model) topicTable(w, budget int) string {
return styledTable(headers, rows, tw, pad)
}
+// solveWidths settles the name column and the table width once the column set is fixed.
+// The name column gets whatever the numeric block leaves behind, within its bounds. If
+// even the minimum does not fit, it retries with compact padding before letting the table
+// clamp -- a clamped table shrinks columns of its own choosing -- and returns the padding
+// it settled on, since the table must be drawn with the same one.
+func solveWidths(w int, specs []colSpec, cells []map[string]string, pad int) (nameW, tableW, usedPad int) {
+ numeric := colWidths(specs, cells)
+ nameW = firstColWidth(w, numeric, pad)
+ if nameW < minNameWidth && pad > 2 {
+ pad = 2
+ nameW = firstColWidth(w, numeric, pad)
+ }
+ nameW = max(min(nameW, maxNameWidth), minNameWidth)
+ tableW = min(w, nameW+pad+2+sumPlus(numeric, pad))
+ return nameW, tableW, pad
+}
+
func sumPlus(ws []int, pad int) int {
total := 0
for _, w := range ws {
@@ -700,33 +723,38 @@ func (m model) totalsBar(w int, flowsShown bool) string {
// Each level sheds the least essential remaining piece: bytes, then the sparkline,
// then the rates, then the words themselves.
- build := func(level int) string {
+ build := func(level shedLevel) string {
+ showBytes := totBytes > 0 && level < levelNoBytes
+ showSpark := level < levelNoSpark
+ showRates := haveRates && level < levelNoRates
+ compact := level >= levelCompact
+
segs := []string{headerStyle.Render("TOTAL")}
- if level < 4 {
+ if compact {
+ segs = append(segs,
+ prodBold.Render("↑ "+comma(s.TotalProduced)),
+ consBold.Render("↓ "+comma(s.TotalConsumed)))
+ } else {
prod := prodBold.Render(comma(s.TotalProduced)) + dimStyle.Render(" produced")
cons := consBold.Render(comma(s.TotalConsumed)) + dimStyle.Render(" consumed")
- if haveRates && level < 3 {
+ if showRates {
prod += dimStyle.Render(" · ") + prodStyle.Render(humanRate(pr))
cons += dimStyle.Render(" · ") + consStyle.Render(humanRate(cr))
}
segs = append(segs, prod, cons)
- } else {
- segs = append(segs,
- prodBold.Render("↑ "+comma(s.TotalProduced)),
- consBold.Render("↓ "+comma(s.TotalConsumed)))
}
segs = append(segs, dimStyle.Render("lag ")+lagCell(s.TotalProduced-s.TotalConsumed))
if brokerSeg != "" {
segs = append(segs, brokerSeg)
}
- if totBytes > 0 && level < 1 {
+ if showBytes {
bs := dimStyle.Render(humanBytes(totBytes))
if haveRates {
bs += dimStyle.Render(" · " + humanByteRate(br))
}
segs = append(segs, bs)
}
- if level < 2 {
+ if showSpark {
if sv := m.sparkVals(8); sv != nil {
segs = append(segs, prodStyle.Render(sparkline(sv)))
}
@@ -742,19 +770,31 @@ func (m model) totalsBar(w int, flowsShown bool) string {
segs = append(segs, dimStyle.Render(plural(int64(len(s.Flows)), "flow")+" not shown"))
}
sep := " "
- if level >= 4 {
+ if compact {
sep = " "
}
return " " + strings.Join(segs, sep)
}
- for level := 0; level <= 4; level++ {
+ for level := levelFull; level <= levelCompact; level++ {
if line := build(level); lipgloss.Width(line) <= w {
return line
}
}
- return truncate(build(4), w)
+ return truncate(build(levelCompact), w)
}
+// shedLevel is a rung of the totals bar's degradation ladder. Each rung keeps everything
+// the rungs below it keep and sheds one more piece.
+type shedLevel int
+
+const (
+ levelFull shedLevel = iota // everything
+ levelNoBytes // drops the byte count and byte rate
+ levelNoSpark // also drops the sparkline
+ levelNoRates // also drops the per-second rates
+ levelCompact // arrows for words, and tighter separators
+)
+
// issuesLine surfaces produce/consume/commit errors and duplicates as one aggregated line,
// present only when something is non-zero, so a clean run pays no space for it.
func (m model) issuesLine(w int) string {
diff --git a/manual_testing/README.md b/manual_testing/README.md
index 1ca1345..f0e2f1a 100644
--- a/manual_testing/README.md
+++ b/manual_testing/README.md
@@ -33,8 +33,9 @@ cd manual_testing
./upload-schema.sh orders-value order-schema.avsc
```
-Both arguments are optional and default to exactly those values. The registry URL comes from
-`$SCHEMA_REGISTRY_URL`, defaulting to `http://localhost:8081`.
+Both arguments are optional and default to exactly those values; an optional third argument
+is the schema type (`AVRO`, `PROTOBUF` or `JSON`), defaulting to `AVRO`. The registry URL
+comes from `$SCHEMA_REGISTRY_URL`, defaulting to `http://localhost:8081`.
## 3. Verify the schema landed
@@ -71,11 +72,12 @@ carries a `uuid` logical type on a string, an enum, and a `timestamp-millis` lon
## Upload a custom schema
```bash
-./upload-schema.sh <subject-name> <schema-file>
+./upload-schema.sh <subject-name> <schema-file> [schema-type]
# Examples:
./upload-schema.sh users-value user-schema.avsc
./upload-schema.sh payments-value payment-schema.avsc
+./upload-schema.sh events-value event.json JSON
```
Whatever subject you pick has to match the `subject_name` of the topic in your scenario file.
diff --git a/manual_testing/upload-schema.sh b/manual_testing/upload-schema.sh
index 4585df3..09830ef 100755
--- a/manual_testing/upload-schema.sh
+++ b/manual_testing/upload-schema.sh
@@ -4,6 +4,7 @@ set -e
SCHEMA_REGISTRY_URL="${SCHEMA_REGISTRY_URL:-http://localhost:8081}"
SUBJECT="${1:-orders-value}"
SCHEMA_FILE="${2:-order-schema.avsc}"
+SCHEMA_TYPE="${3:-AVRO}"
if [ ! -f "$SCHEMA_FILE" ]; then
echo "Error: Schema file '$SCHEMA_FILE' not found"
@@ -15,11 +16,12 @@ SCHEMA=$(cat "$SCHEMA_FILE" | jq -c '.')
echo "Uploading schema to subject: $SUBJECT"
echo "Schema Registry URL: $SCHEMA_REGISTRY_URL"
+echo "Schema type: $SCHEMA_TYPE"
# Register the schema
RESPONSE=$(curl -s -X POST \
-H "Content-Type: application/vnd.schemaregistry.v1+json" \
- --data "{\"schemaType\": \"AVRO\", \"schema\": $(echo "$SCHEMA" | jq -Rs '.')}" \
+ --data "{\"schemaType\": \"$SCHEMA_TYPE\", \"schema\": $(echo "$SCHEMA" | jq -Rs '.')}" \
"$SCHEMA_REGISTRY_URL/subjects/$SUBJECT/versions")
echo "Response: $RESPONSE"