From c741c9a5e180fd4122dc420acaf64923922eb5f6 Mon Sep 17 00:00:00 2001 From: Dheeren Date: Tue, 1 Dec 2026 13:18:57 +0530 Subject: [PATCH 01/11] sink: optional gRPC call and stream rows Config-driven and off by default: correlation.grpcCallMetric forms one call row per sample, correlation.grpcStreamMetrics sums the stream counters per time bucket (grpcStreamBucket, default 10s) and row key. Call rows get the gRPC row name, status (NO_STATUS when absent), enum status message and error count; the reflection call ending CANCELLED forms no row, marks no data and labels no check. A finished call becomes its VU's last request for check correlation. New computed values protocol, streamsOpened, msgsSent and msgsReceived, and a column option omitEmpty that leaves an empty value out, so request and WebSocket rows stay byte-for-byte unchanged. --- README.md | 73 +++- internal/sink/buffer.go | 23 +- internal/sink/columns.go | 76 +++- internal/sink/config.go | 131 +++++- internal/sink/grpc.go | 248 +++++++++++ internal/sink/grpc_test.go | 862 +++++++++++++++++++++++++++++++++++++ internal/sink/sink.go | 20 +- 7 files changed, 1404 insertions(+), 29 deletions(-) create mode 100644 internal/sink/grpc.go create mode 100644 internal/sink/grpc_test.go diff --git a/README.md b/README.md index b3b0e51..169a4e0 100644 --- a/README.md +++ b/README.md @@ -109,8 +109,9 @@ Rows are posted as `JSONEachRow` to a ClickHouse-HTTP-compatible endpoint | `summary` | a one-line run summary file written at stop; see below | Every key added after the first release (`correlation.verdictMetric`, -`correlation.joinMetrics`, `hold`, `summary`, `cardinality.exemptMetrics` and the -column bounds) is optional; without them rows are byte-for-byte what they were. +`correlation.joinMetrics`, the `correlation.grpc*` keys, `hold`, `summary`, +`cardinality.exemptMetrics`, the column bounds and `omitEmpty`) is optional; +without them rows are byte-for-byte what they were. #### Columns @@ -130,13 +131,20 @@ WebSocket), `errorCount`, `url` (method-prefixed real URL), `requestName` (method-prefixed name tag, or the metric name on WebSocket rows), `group`, `vus`, `duration`, `latency`, `connect`, `bytesSent`, `bytesReceived`. +gRPC rows (see [gRPC rows](#grpc-rows)) read the same built-ins plus `protocol` +(empty on request and WebSocket rows, `grpc` or `grpc_stream` on gRPC rows), +`streamsOpened`, `msgsSent` and `msgsReceived` (0 on every other row). +`protocol` requires `correlation.grpcCallMetric` or `grpcStreamMetrics`; the three +counters require `grpcStreamMetrics`. + Request rows can also read `failedVerdict`: `1` when the `correlation.verdictMetric` sample reported a failure, `0` when it reported success and `-1` when none arrived (and on WebSocket rows). It requires `correlation.verdictMetric`. Check rows (`assertionColumns`): `timestamp`, `parentLabel` and `parentStatus` -(the name/url and status of the same VU's previous request), `failed`. +(the name/url and status of the same VU's previous request, or its previous gRPC +call when gRPC rows are configured), `failed`. Numeric and boolean built-ins cannot be part of a fallback list. @@ -151,6 +159,10 @@ A string-sourced column can carry optional bounds: | `when` | `[{source, equals}]`: all must hold, else the column is empty (`0` for `uint`); without `equals` a condition holds on any non-empty value | | `joinDefault` | written on a row a join sample reached when the sources give no valid value; requires `correlation.joinMetrics` | +Any column, computed ones included, can set `omitEmpty: true`: the column is +left out of a row whose value is `""`, `0` or `false`. Use it for columns only +some rows carry, such as the gRPC ones, so the other rows stay unchanged. + #### Correlation | Key | Meaning | @@ -164,6 +176,57 @@ A string-sourced column can carry optional bounds: | `checkMetric` | the check metric (`checks`) | | `verdictMetric` | a per-request pass/fail metric (e.g. `http_req_failed`), joined to its request by the same key as the phase metrics; feeds `computed:failedVerdict` | | `joinMetrics` | metrics that never form rows: each sample's metadata is merged into the request row carrying the same `bytesIdMetaKey` id (requires `bytesIdMetaKey`). A sample that finds no row adds its value (1 to 1e6, anything else counts as 1) to the `unjoined` counter | +| `grpcCallMetric` | the metric that forms one gRPC call row per sample (k6: `grpc_req_duration`) | +| `grpcStreamMetrics` | `{streamsOpened, msgsSent, msgsReceived}`: the gRPC stream counters (k6: `grpc_streams`, `grpc_streams_msgs_sent`, `grpc_streams_msgs_received`), each optional | +| `grpcReflectionName` | the row name of a call with no `name`, `service`/`method` or `url` tag (k6's server-reflection call); default `__grpc_reflection_connect__`; requires `grpcCallMetric` | +| `grpcStreamBucket` | the time bucket stream counters are summed in (default `10s`); requires `grpcStreamMetrics` | + +#### gRPC rows + +Off unless `correlation.grpcCallMetric` or `grpcStreamMetrics` is set; until then +gRPC samples form no rows. Names are matched exactly, so a script's own `grpc_*` +metrics are never gRPC rows. + +- **Call rows**: every `grpcCallMetric` sample is one row on arrival. `requestName` + is the `name` tag, else `//`, else the `url` tag from its first + `/`, else `grpcReflectionName`; `url` is the `url` tag as is; `status` is the + `status` tag, or `NO_STATUS` when absent; `statusMessage` is the gRPC enum name + for 0 to 16 (`OK` ... `UNAUTHENTICATED`), else the status itself; `errorCount` is + 0 only for status `0`; `duration` is the call time. With `sendTimeRestamp` the + row is stamped at the send instant (sample time minus duration). +- **The reflection call ending `CANCELLED`** (status `1` on a call named + `grpcReflectionName`) forms no row, marks no script data and is never a check's + parent. k6 cancels the reflection stream when `connect()` returns, so that + status is not a call. Every other reflection status is written, and a named call + ending `CANCELLED` stays an error. +- **Stream rows**: the stream counters are summed per `grpcStreamBucket`, row + name, `url`, `scenario`, `group` and every tag and metadata value the columns + read, until the next flush, into one row each: `protocol` `grpc_stream`, the + three counters, empty `status` and `statusMessage`, `duration` and `errorCount` + 0, stamped at the first sample. +- gRPC rows leave on every flush, count as pending for the push marker, share the + `buffers.metricMax` cap (overflow is shed and counted) and mark `scriptData`. + A finished call becomes its VU's last request for check correlation (label = + `requestName`, status = `status`). + +```json +{ + "correlation": { + "grpcCallMetric": "grpc_req_duration", + "grpcStreamMetrics": {"streamsOpened": "grpc_streams", "msgsSent": "grpc_streams_msgs_sent", + "msgsReceived": "grpc_streams_msgs_received"} + }, + "columns": [ + {"name": "protocol", "from": "computed:protocol", "omitEmpty": true}, + {"name": "streamsOpened", "from": "computed:streamsOpened", "omitEmpty": true}, + {"name": "msgsSent", "from": "computed:msgsSent", "omitEmpty": true}, + {"name": "msgsReceived", "from": "computed:msgsReceived", "omitEmpty": true} + ] +} +``` + +(Only the keys gRPC adds are shown.) With `omitEmpty`, request and WebSocket +rows carry none of these columns and stay byte-for-byte what they were. #### Hold @@ -178,8 +241,8 @@ the same marker, is then not counted again. Requires `correlation.joinMetrics`. `{dir, totalRows, scriptData, pushAttempted, iteration, iterationThreshold, dataMetricPrefixes}`. `totalRows` holds the number of rows delivered. The others are written once with -`1`: `scriptData` on the first sample whose metric is the check metric or starts -with a `dataMetricPrefixes` entry, `pushAttempted` before the first POST, and +`1`: `scriptData` on the first sample whose metric is the check metric, a gRPC +row metric or starts with a `dataMetricPrefixes` entry, `pushAttempted` before the first POST, and `iteration` after `iterationThreshold` (default 3) iterations. Stale markers are removed at start. An empty name disables that marker. diff --git a/internal/sink/buffer.go b/internal/sink/buffer.go index 67133d3..636fabe 100644 --- a/internal/sink/buffer.go +++ b/internal/sink/buffer.go @@ -51,6 +51,8 @@ type rowEngine struct { hold *HoldConfig // distinctCols are the indexes of the columns with a distinct budget. distinctCols []int + // grpc forms gRPC call and stream rows; nil when none is configured. + grpc *grpcEngine } // builtinTags are the tags the computed request values read. @@ -86,6 +88,7 @@ func newRowEngine(cfg *Config) *rowEngine { joinMetrics: toSet(cfg.Correlation.JoinMetrics), hold: cfg.Hold, distinctCols: distinctCols, + grpc: newGRPCEngine(&cfg.Correlation, cols), } } @@ -205,6 +208,10 @@ type metricBuffer struct { dropped uint64 wsRows []row wsSums map[string]*wsSummed + // grpcRows are rendered call rows; grpcSums stream counters per key until + // the next drain. Both bounded by maxEntries, under mu. + grpcRows []row + grpcSums map[string]*rowView // holdMax bounds how long a pending row waits for its join; unjoined counts // join samples that found no row and held rows that expired. Both under mu. holdMax time.Duration @@ -225,6 +232,7 @@ func newMetricBuffer(engine *rowEngine, maxEntries int, staleAfter time.Duration byBytesReqID: make(map[string]string), maxEntries: maxEntries, wsSums: make(map[string]*wsSummed), + grpcSums: make(map[string]*rowView), } if h := engine.hold; h != nil { // A held row must leave before staleAfter would drop it. @@ -236,6 +244,11 @@ func newMetricBuffer(engine *rowEngine, maxEntries int, staleAfter time.Duration func (b *metricBuffer) add(sample metrics.Sample) { e := b.engine metricName := sampleMetricName(sample) + // gRPC rows are complete on arrival; nothing correlates with them. + if e.grpc.isRowMetric(metricName) { + b.addGRPC(sample, metricName) + return + } if _, ok := e.wsMetrics[metricName]; ok { b.addWS(sample, metricName, false) return @@ -465,7 +478,7 @@ func (b *metricBuffer) drainWSLocked() []row { } // drainReady returns complete requests last seen before completeBefore, drops -// stale incomplete ones, and returns every WebSocket row. +// stale incomplete ones, and returns every gRPC and WebSocket row. func (b *metricBuffer) drainReady(completeBefore time.Time) []row { b.mu.Lock() defer b.mu.Unlock() @@ -489,6 +502,7 @@ func (b *metricBuffer) drainReady(completeBefore time.Time) []row { b.removeEntry(id, entry) } } + rows = append(rows, b.drainGRPCLocked()...) return append(rows, b.drainWSLocked()...) } @@ -506,6 +520,7 @@ func (b *metricBuffer) drainAll() []row { } b.removeEntry(id, entry) } + rows = append(rows, b.drainGRPCLocked()...) return append(rows, b.drainWSLocked()...) } @@ -533,12 +548,12 @@ func (b *metricBuffer) droppedCount() uint64 { return b.dropped } -// pending counts buffered requests that can still become rows. An entry with no -// request line never does, so it must not hold this above zero. +// pending counts buffered requests and gRPC rows that can still become rows. +// An entry with no request line never does, so it must not hold this above zero. func (b *metricBuffer) pending() int { b.mu.Lock() defer b.mu.Unlock() - n := 0 + n := len(b.grpcRows) + len(b.grpcSums) for _, entry := range b.entries { if entry.hasRequestLine { n++ diff --git a/internal/sink/columns.go b/internal/sink/columns.go index 0379d96..2f0e3dc 100644 --- a/internal/sink/columns.go +++ b/internal/sink/columns.go @@ -46,6 +46,16 @@ type rowView struct { verdictFailed bool joined bool resolved map[int]string + + // gRPC rows only: proto is protocolGRPC or protocolGRPCStream (empty on + // every other row), grpcName the row name, grpcCode a call's status code, + // and the stream counters of a summed stream row. + proto string + grpcName string + grpcCode string + streamsOpened int64 + msgsSent int64 + msgsReceived int64 } type builtin struct { @@ -56,11 +66,16 @@ type builtin struct { } // requestBuiltins are the computed values available to sink.columns. Each one -// covers both HTTP request rows and WebSocket rows. +// covers HTTP request rows, WebSocket rows and gRPC rows. var requestBuiltins = map[string]builtin{ - "timestamp": {kind: kindInt, num: func(v *rowView) int64 { return v.timestamp }}, - "scenario": {kind: kindString, str: func(v *rowView) string { return nonEmpty(v.tags["scenario"], "default") }}, - "status": {kind: kindString, str: func(v *rowView) string { return nonEmpty(v.tags["status"], "0") }}, + "timestamp": {kind: kindInt, num: func(v *rowView) int64 { return v.timestamp }}, + "scenario": {kind: kindString, str: func(v *rowView) string { return nonEmpty(v.tags["scenario"], "default") }}, + "status": {kind: kindString, str: func(v *rowView) string { + if v.proto != "" { + return v.grpcCode + } + return nonEmpty(v.tags["status"], "0") + }}, "statusMessage": {kind: kindString, str: statusMessage}, "errorCount": {kind: kindInt, num: errorCount}, "url": {kind: kindString, str: rowURL}, @@ -89,6 +104,12 @@ var requestBuiltins = map[string]builtin{ return 0 } }}, + // protocol is empty on HTTP and WebSocket rows; gRPC rows carry + // protocolGRPC or protocolGRPCStream. + "protocol": {kind: kindString, str: func(v *rowView) string { return v.proto }}, + "streamsOpened": {kind: kindInt, num: func(v *rowView) int64 { return v.streamsOpened }}, + "msgsSent": {kind: kindInt, num: func(v *rowView) int64 { return v.msgsSent }}, + "msgsReceived": {kind: kindInt, num: func(v *rowView) int64 { return v.msgsReceived }}, } // assertionBuiltins are the computed values available to sink.assertionColumns. @@ -132,6 +153,7 @@ type column struct { budget *distinctBudget joinDefault *string joinDefaultNum uint64 // joinDefault parsed, for kindUint + omitEmpty bool // leave the column out when its value is "", 0 or false } // condition holds when its source reads equals, or any non-empty value when @@ -193,7 +215,7 @@ func compileColumns(specs []ColumnSpec, builtins map[string]builtin, constants m return nil, fmt.Errorf("%s.from: at least one source is required", where) } key, _ := json.Marshal(spec.Name) - col := column{key: append(key, ':'), kind: kindString} + col := column{key: append(key, ':'), kind: kindString, omitEmpty: spec.OmitEmpty} for j, raw := range spec.From { src, kind, err := parseSource(raw, builtins, constants) if err != nil { @@ -351,23 +373,39 @@ func parseSource(raw string, builtins map[string]builtin, constants map[string]s // escaping matches a json.Marshal of an equivalent struct byte for byte. func (cols columns) appendRow(buf []byte, v *rowView) []byte { buf = append(buf, '{') + written := 0 for i := range cols { c := &cols[i] - if i > 0 { + start := len(buf) + if written > 0 { buf = append(buf, ',') } buf = append(buf, c.key...) + var empty bool switch c.kind { case kindInt: - buf = strconv.AppendInt(buf, c.sources[0].builtin.num(v), 10) + n := c.sources[0].builtin.num(v) + empty = n == 0 + buf = strconv.AppendInt(buf, n, 10) case kindBool: - buf = strconv.AppendBool(buf, c.sources[0].builtin.boolean(v)) + b := c.sources[0].builtin.boolean(v) + empty = !b + buf = strconv.AppendBool(buf, b) case kindUint: - buf = strconv.AppendUint(buf, c.uintValue(v), 10) + n := c.uintValue(v) + empty = n == 0 + buf = strconv.AppendUint(buf, n, 10) default: - encoded, _ := json.Marshal(c.stringValue(i, v)) + value := c.stringValue(i, v) + empty = value == "" + encoded, _ := json.Marshal(value) buf = append(buf, encoded...) } + if empty && c.omitEmpty { + buf = buf[:start] + continue + } + written++ } return append(buf, '}') } @@ -464,6 +502,9 @@ func truncateRunes(s string, n int) string { } func statusMessage(v *rowView) string { + if v.proto != "" { + return grpcStatusMessage(v.grpcCode) + } status := nonEmpty(v.tags["status"], "0") if v.ws { if v.wsMessage != "" { @@ -481,6 +522,15 @@ func statusMessage(v *rowView) string { } func errorCount(v *rowView) int64 { + switch v.proto { + case protocolGRPC: + if v.grpcCode == grpcStatusOK { + return 0 + } + return 1 + case protocolGRPCStream: + return 0 + } status := nonEmpty(v.tags["status"], "0") if v.ws { if status == "101" { @@ -497,6 +547,9 @@ func errorCount(v *rowView) int64 { // requestName is the request's name tag (or its url tag when unnamed), // prefixed with the method. WebSocket rows carry their metric name instead. func requestName(v *rowView) string { + if v.proto != "" { + return v.grpcName + } if v.ws { return v.wsMetric } @@ -511,6 +564,9 @@ func requestName(v *rowView) string { // tag with the name tag on named requests, so the real URL comes from metadata // or a legacy tag when either is present. func rowURL(v *rowView) string { + if v.proto != "" { + return v.tags["url"] + } if v.ws { return nonEmpty(v.tags["url"], "unknown") } diff --git a/internal/sink/config.go b/internal/sink/config.go index 59a016c..363f2f1 100644 --- a/internal/sink/config.go +++ b/internal/sink/config.go @@ -1,4 +1,4 @@ -// Package sink is the output capability: it posts request, WebSocket and +// Package sink is the output capability: it posts request, WebSocket, gRPC and // check rows as JSONEachRow to a ClickHouse-HTTP-compatible endpoint, writes // the run-progress markers and enforces the time-series cardinality budget. package sink @@ -107,6 +107,42 @@ type CorrelationConfig struct { // JoinMetrics never form rows: their metadata is merged into the request row // whose bytesIdMetaKey id they carry. JoinMetrics []string `json:"joinMetrics,omitempty"` + // GRPCCallMetric forms one gRPC call row per sample (k6: grpc_req_duration). + GRPCCallMetric string `json:"grpcCallMetric,omitempty"` + // GRPCStreamMetrics are gRPC stream counters summed per key and time bucket. + GRPCStreamMetrics *GRPCStreamMetrics `json:"grpcStreamMetrics,omitempty"` + // GRPCReflectionName names a gRPC call with no name, service/method or url + // tag; empty means defaultGRPCReflectionName. + GRPCReflectionName string `json:"grpcReflectionName,omitempty"` + // GRPCStreamBucket is the time bucket stream counters are summed in. + GRPCStreamBucket Duration `json:"grpcStreamBucket,omitempty"` +} + +// GRPCStreamMetrics names the stream counters, each optional (k6: +// grpc_streams, grpc_streams_msgs_sent, grpc_streams_msgs_received). +type GRPCStreamMetrics struct { + StreamsOpened string `json:"streamsOpened,omitempty"` + MsgsSent string `json:"msgsSent,omitempty"` + MsgsReceived string `json:"msgsReceived,omitempty"` +} + +// names lists the configured stream counters. +func (g *GRPCStreamMetrics) names() []string { + if g == nil { + return nil + } + var out []string + for _, n := range []string{g.StreamsOpened, g.MsgsSent, g.MsgsReceived} { + if n != "" { + out = append(out, n) + } + } + return out +} + +// grpcEnabled reports whether any gRPC row is configured. +func (c *CorrelationConfig) grpcEnabled() bool { + return c.GRPCCallMetric != "" || len(c.GRPCStreamMetrics.names()) > 0 } // MarkersConfig names the run-progress marker files. An empty name disables that marker. @@ -148,6 +184,8 @@ type ColumnSpec struct { // JoinDefault is written on a row a join sample reached when the sources // give no valid value. JoinDefault *string `json:"joinDefault,omitempty"` + // OmitEmpty leaves the column out of a row whose value is empty ("", 0 or false). + OmitEmpty bool `json:"omitEmpty,omitempty"` } // DistinctSpec caps the distinct values of a column per process. Values beyond @@ -263,6 +301,9 @@ func (s *Config) Validate() error { } } } + if err := s.validateGRPC(); err != nil { + return err + } if err := s.validateJoins(); err != nil { return err } @@ -273,16 +314,28 @@ func (s *Config) Validate() error { // never given two roles. func (s *Config) rowMetrics() map[string]string { c := &s.Correlation - roles := map[string]string{} - add := func(role string, names ...string) { - for _, n := range names { - if n != "" { - if _, taken := roles[n]; !taken { - roles[n] = role - } + roles := s.baseRowMetrics() + addRole(roles, "the gRPC call metric", c.GRPCCallMetric) + addRole(roles, "a gRPC stream metric", c.GRPCStreamMetrics.names()...) + return roles +} + +// addRole gives each name a role unless it already has one. +func addRole(roles map[string]string, role string, names ...string) { + for _, n := range names { + if n != "" { + if _, taken := roles[n]; !taken { + roles[n] = role } } } +} + +// baseRowMetrics is rowMetrics without the gRPC metrics. +func (s *Config) baseRowMetrics() map[string]string { + c := &s.Correlation + roles := map[string]string{} + add := func(role string, names ...string) { addRole(roles, role, names...) } for name := range httpPhaseMetrics { add("an HTTP request metric", name) } @@ -293,6 +346,68 @@ func (s *Config) rowMetrics() map[string]string { return roles } +// grpcBuiltins are the computed values that read only gRPC rows. +var grpcBuiltins = map[string]bool{ + "computed:protocol": false, + "computed:streamsOpened": true, + "computed:msgsSent": true, + "computed:msgsReceived": true, +} + +// validateGRPC checks the gRPC metrics and the columns that read them. +func (s *Config) validateGRPC() error { + c := &s.Correlation + roles := s.baseRowMetrics() + claim := func(where, name, role string) error { + if prev, taken := roles[name]; taken { + return fmt.Errorf("%s: %q is already %s", where, name, prev) + } + roles[name] = role + return nil + } + if c.GRPCCallMetric != "" { + if err := claim("sink.correlation.grpcCallMetric", c.GRPCCallMetric, "the gRPC call metric"); err != nil { + return err + } + } + if g := c.GRPCStreamMetrics; g != nil { + if len(g.names()) == 0 { + return errors.New("sink.correlation.grpcStreamMetrics: name at least one of streamsOpened, msgsSent, msgsReceived") + } + for _, f := range []struct{ key, name string }{ + {"streamsOpened", g.StreamsOpened}, {"msgsSent", g.MsgsSent}, {"msgsReceived", g.MsgsReceived}, + } { + if f.name == "" { + continue + } + if err := claim("sink.correlation.grpcStreamMetrics."+f.key, f.name, "a gRPC stream metric"); err != nil { + return err + } + } + } + if c.GRPCReflectionName != "" && c.GRPCCallMetric == "" { + return errors.New("sink.correlation.grpcReflectionName: requires sink.correlation.grpcCallMetric") + } + if c.GRPCStreamBucket != 0 && c.GRPCStreamMetrics == nil { + return errors.New("sink.correlation.grpcStreamBucket: requires sink.correlation.grpcStreamMetrics") + } + for i, spec := range s.Columns { + for _, src := range spec.From { + streamOnly, ok := grpcBuiltins[src] + if !ok { + continue + } + if streamOnly && c.GRPCStreamMetrics == nil { + return fmt.Errorf("sink.columns[%d].from: %s requires sink.correlation.grpcStreamMetrics", i, src) + } + if !c.grpcEnabled() { + return fmt.Errorf("sink.columns[%d].from: %s requires sink.correlation.grpcCallMetric or grpcStreamMetrics", i, src) + } + } + } + return nil +} + // validateJoins checks the verdict metric, the join metrics, the hold and the // column options that depend on them. func (s *Config) validateJoins() error { diff --git a/internal/sink/grpc.go b/internal/sink/grpc.go new file mode 100644 index 0000000..78f51c9 --- /dev/null +++ b/internal/sink/grpc.go @@ -0,0 +1,248 @@ +package sink + +import ( + "sort" + "strconv" + "strings" + "time" + + "go.k6.io/k6/v2/metrics" +) + +const ( + // defaultGRPCReflectionName names a call with no name, service/method or url + // tag: k6's server-reflection call. A real method path starts with "/". + defaultGRPCReflectionName = "__grpc_reflection_connect__" + defaultGRPCStreamBucket = 10 * time.Second + // grpcNoStatus is the status of a call recorded without a status tag. It is + // not a gRPC status name, so it never reads as UNKNOWN (2). + grpcNoStatus = "NO_STATUS" + grpcStatusOK = "0" + grpcStatusCancelled = "1" + protocolGRPC = "grpc" + protocolGRPCStream = "grpc_stream" +) + +// grpcStatusNames maps gRPC status codes 0 to 16 to their enum names. +var grpcStatusNames = [...]string{ + "OK", "CANCELLED", "UNKNOWN", "INVALID_ARGUMENT", "DEADLINE_EXCEEDED", + "NOT_FOUND", "ALREADY_EXISTS", "PERMISSION_DENIED", "RESOURCE_EXHAUSTED", + "FAILED_PRECONDITION", "ABORTED", "OUT_OF_RANGE", "UNIMPLEMENTED", + "INTERNAL", "UNAVAILABLE", "DATA_LOSS", "UNAUTHENTICATED", +} + +// grpcCounter is the stream counter a stream metric adds to. +type grpcCounter int + +const ( + counterStreamsOpened grpcCounter = iota + counterMsgsSent + counterMsgsReceived +) + +// grpcEngine is the gRPC part of the row engine; nil when no gRPC row is configured. +type grpcEngine struct { + callMetric string + streamMetrics map[string]grpcCounter + reflectionName string + bucket time.Duration + // keyTags / keyMeta are the tag and metadata keys the columns read; stream + // samples that differ on any of them are summed into separate rows. + keyTags []string + keyMeta []string +} + +func newGRPCEngine(c *CorrelationConfig, cols columns) *grpcEngine { + if !c.grpcEnabled() { + return nil + } + g := &grpcEngine{ + callMetric: c.GRPCCallMetric, + streamMetrics: map[string]grpcCounter{}, + reflectionName: nonEmpty(c.GRPCReflectionName, defaultGRPCReflectionName), + bucket: c.GRPCStreamBucket.or(defaultGRPCStreamBucket), + } + if s := c.GRPCStreamMetrics; s != nil { + for name, counter := range map[string]grpcCounter{ + s.StreamsOpened: counterStreamsOpened, s.MsgsSent: counterMsgsSent, s.MsgsReceived: counterMsgsReceived, + } { + if name != "" { + g.streamMetrics[name] = counter + } + } + } + tags, meta := map[string]struct{}{}, map[string]struct{}{} + for i := range cols { + for _, s := range cols[i].allSources() { + switch { + case s.isTag: + tags[s.tag] = struct{}{} + case s.isMeta: + meta[s.meta] = struct{}{} + } + } + } + g.keyTags, g.keyMeta = sortedSet(tags), sortedSet(meta) + return g +} + +func sortedSet(m map[string]struct{}) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +} + +// isRowMetric reports whether the metric forms gRPC rows. Names match exactly: +// a script's own metrics may start with "grpc_" too. +func (g *grpcEngine) isRowMetric(name string) bool { + if g == nil || name == "" { + return false + } + if name == g.callMetric { + return true + } + _, ok := g.streamMetrics[name] + return ok +} + +// isCall reports whether the metric is the call metric. +func (g *grpcEngine) isCall(name string) bool { + return g != nil && name != "" && name == g.callMetric +} + +// rowName is the name tag, else //, else the path part of the +// url tag (k6 writes host:port/package.Service/Method), else the reflection name. +func (g *grpcEngine) rowName(tags map[string]string) string { + if name := tags["name"]; name != "" { + return name + } + if service, method := tags["service"], tags["method"]; service != "" && method != "" { + return "/" + service + "/" + method + } + if url := tags["url"]; url != "" { + if i := strings.Index(url, "/"); i >= 0 { + return url[i:] + } + return url + } + return g.reflectionName +} + +// grpcStatusCode is the status tag, or grpcNoStatus when it is absent. +func grpcStatusCode(tags map[string]string) string { + return nonEmpty(tags["status"], grpcNoStatus) +} + +// grpcStatusMessage is the enum name of a status code, or the code itself when +// it is not one of 0 to 16. +func grpcStatusMessage(code string) string { + n, err := strconv.Atoi(code) + if err != nil || n < 0 || n >= len(grpcStatusNames) || strconv.Itoa(n) != code { + return code + } + return grpcStatusNames[n] +} + +// dropsCall reports a call sample that forms no row, marks no data and labels +// no check: the reflection call ending CANCELLED. k6 cancels the reflection +// stream when connect() returns, so that CANCELLED is not a call; native k6 +// reports a successful lookup with no call sample at all. Every other +// reflection status is kept, and a named call ending CANCELLED stays an error. +func (g *grpcEngine) dropsCall(metricName string, tags map[string]string) bool { + return g.isCall(metricName) && tags["status"] == grpcStatusCancelled && g.rowName(tags) == g.reflectionName +} + +// streamKey groups stream samples by time bucket, row name and every tag and +// metadata value a column reads, so a summed row never mixes two renderings. +func (g *grpcEngine) streamKey(tags, meta map[string]string, at time.Time) string { + var b strings.Builder + b.WriteString(strconv.FormatInt(at.Truncate(g.bucket).UnixNano(), 10)) + for _, part := range []string{g.rowName(tags), tags["url"], tags["scenario"], tags["group"]} { + b.WriteByte('|') + b.WriteString(sanitizeKeyPart(part)) + } + for _, k := range g.keyTags { + b.WriteString("|t:") + b.WriteString(sanitizeKeyPart(tags[k])) + } + for _, k := range g.keyMeta { + b.WriteString("|m:") + b.WriteString(sanitizeKeyPart(meta[k])) + } + return b.String() +} + +// addGRPC buffers a gRPC sample: one rendered row per call sample, and stream +// counters summed into one row per key until the next drain. +func (b *metricBuffer) addGRPC(sample metrics.Sample, metricName string) { + e := b.engine + g := e.grpc + tags := extractTags(sample) + if g.dropsCall(metricName, tags) { + return + } + meta := extractMeta(sample) + + b.mu.Lock() + defer b.mu.Unlock() + + if g.isCall(metricName) { + if len(b.grpcRows) >= b.maxEntries { + b.dropped++ + return + } + elapsed := roundedInt64(sample.Value) + ts := sample.Time.UnixMilli() + if e.sendTimeRestamp { + // k6 emits the sample when the call ends; stamp the send instant. + ts -= elapsed + } + v := rowView{ + tags: tags, meta: meta, corr: e.corr, timestamp: ts, duration: elapsed, + proto: protocolGRPC, grpcName: g.rowName(tags), grpcCode: grpcStatusCode(tags), + } + b.grpcRows = append(b.grpcRows, e.columns.appendRow(nil, &v)) + return + } + + key := g.streamKey(tags, meta, sample.Time) + acc, exists := b.grpcSums[key] + if !exists { + if len(b.grpcSums) >= b.maxEntries { + b.dropped++ + return + } + acc = &rowView{ + tags: tags, meta: meta, corr: e.corr, timestamp: sample.Time.UnixMilli(), + proto: protocolGRPCStream, grpcName: g.rowName(tags), + } + b.grpcSums[key] = acc + } + value := roundedInt64(sample.Value) + switch g.streamMetrics[metricName] { + case counterStreamsOpened: + acc.streamsOpened += value + case counterMsgsSent: + acc.msgsSent += value + case counterMsgsReceived: + acc.msgsReceived += value + } +} + +// drainGRPCLocked returns the call rows plus one row per stream key, and resets +// both. Caller holds b.mu. +func (b *metricBuffer) drainGRPCLocked() []row { + rows := b.grpcRows + b.grpcRows = nil + if len(b.grpcSums) == 0 { + return rows + } + for _, acc := range b.grpcSums { + rows = append(rows, b.engine.columns.appendRow(nil, acc)) + } + b.grpcSums = make(map[string]*rowView) + return rows +} diff --git a/internal/sink/grpc_test.go b/internal/sink/grpc_test.go new file mode 100644 index 0000000..e7cea4d --- /dev/null +++ b/internal/sink/grpc_test.go @@ -0,0 +1,862 @@ +package sink + +import ( + "encoding/json" + "path/filepath" + "sort" + "strings" + "testing" + "time" + + "go.k6.io/k6/v2/metrics" +) + +// k6's gRPC metric names, as a caller would configure them. +const ( + grpcCall = "grpc_req_duration" + grpcStreams = "grpc_streams" + grpcMsgsSent = "grpc_streams_msgs_sent" + grpcMsgsReceived = "grpc_streams_msgs_received" + reflectionName = defaultGRPCReflectionName +) + +// grpcColumnsJSON are the gRPC-only columns; omitEmpty keeps them off HTTP and +// WebSocket rows. +const grpcColumnsJSON = `[ + {"name": "protocol", "from": "computed:protocol", "omitEmpty": true}, + {"name": "streamsOpened", "from": "computed:streamsOpened", "omitEmpty": true}, + {"name": "msgsSent", "from": "computed:msgsSent", "omitEmpty": true}, + {"name": "msgsReceived", "from": "computed:msgsReceived", "omitEmpty": true} +]` + +// withGRPC configures gRPC call and stream rows and their columns. +func withGRPC(c *Config) { + c.Correlation.GRPCCallMetric = grpcCall + c.Correlation.GRPCStreamMetrics = &GRPCStreamMetrics{ + StreamsOpened: grpcStreams, MsgsSent: grpcMsgsSent, MsgsReceived: grpcMsgsReceived, + } + c.Columns = append(c.Columns, mustColumns(grpcColumnsJSON)...) +} + +// grpcRow decodes a row rendered with the base columns plus grpcColumnsJSON. +type grpcRow struct { + testRow + Protocol string `json:"protocol"` + StreamsOpened int64 `json:"streamsOpened"` + MsgsSent int64 `json:"msgsSent"` + MsgsReceived int64 `json:"msgsReceived"` +} + +func decodeGRPCRows(t *testing.T, rows []row) []grpcRow { + t.Helper() + out := make([]grpcRow, len(rows)) + for i, r := range rows { + if err := json.Unmarshal(r, &out[i]); err != nil { + t.Fatalf("row %d is not JSON: %v (%s)", i, err, r) + } + } + return out +} + +func newGRPCBuffer(t *testing.T, maxEntries int) *metricBuffer { + t.Helper() + cfg := testSinkConfig() + withGRPC(cfg) + if err := cfg.Validate(); err != nil { + t.Fatalf("config: %v", err) + } + return newMetricBuffer(newRowEngine(cfg), maxEntries, time.Minute) +} + +// callTags are k6's tags on a finished call; an empty value in extra removes the tag. +func callTags(extra map[string]string) map[string]string { + tags := map[string]string{ + "vu": "3", "scenario": "default", "group": "::checkout", + "name": "/shop.Cart/Add", "url": "cart:50051/shop.Cart/Add", "status": "0", + } + for k, v := range extra { + if v == "" { + delete(tags, k) + continue + } + tags[k] = v + } + return tags +} + +// drainNow drains every row a flush tick would send. +func drainNow(b *metricBuffer) []row { return b.drainReady(time.Now().Add(time.Hour)) } + +func grpcByKey(rows []grpcRow) map[string]grpcRow { + out := map[string]grpcRow{} + for _, r := range rows { + out[r.RequestName+"|"+r.Status] = r + } + return out +} + +// ---- Call rows ---- + +func TestGRPC_CallRow(t *testing.T) { + reg := metrics.NewRegistry() + b := newGRPCBuffer(t, 0) + end := time.UnixMilli(1_700_000_000_500) + b.add(mkSample(reg, grpcCall, callTags(nil), end, 120.4)) + + raw := drainNow(b) + rows := decodeGRPCRows(t, raw) + if len(rows) != 1 { + t.Fatalf("rows = %d, want 1", len(rows)) + } + r := rows[0] + if r.Protocol != "grpc" || r.RequestName != "/shop.Cart/Add" || r.URL != "cart:50051/shop.Cart/Add" { + t.Errorf("protocol/name/url = %q/%q/%q", r.Protocol, r.RequestName, r.URL) + } + if r.Status != "0" || r.StatusMessage != "OK" || r.ErrorCount != 0 { + t.Errorf("status = %q %q err=%d, want 0 OK 0", r.Status, r.StatusMessage, r.ErrorCount) + } + if r.Duration != 120 || r.Group != "::checkout" || r.Scenario != "default" || r.VUs != 3 { + t.Errorf("duration/group/scenario/vus = %d/%q/%q/%d", r.Duration, r.Group, r.Scenario, r.VUs) + } + // Stamped at the send instant, as request rows are. + if r.Timestamp != end.UnixMilli()-120 { + t.Errorf("timestamp = %d, want %d", r.Timestamp, end.UnixMilli()-120) + } + for _, field := range []string{"streamsOpened", "msgsSent", "msgsReceived"} { + if strings.Contains(string(raw[0]), `"`+field+`"`) { + t.Errorf("call row carries %q: %s", field, raw[0]) + } + } +} + +func TestGRPC_CallRowNotReStampedWhenRestampIsOff(t *testing.T) { + cfg := testSinkConfig() + withGRPC(cfg) + cfg.SendTimeRestamp = false + b := newMetricBuffer(newRowEngine(cfg), 0, time.Minute) + end := time.UnixMilli(1_700_000_000_500) + b.add(mkSample(metrics.NewRegistry(), grpcCall, callTags(nil), end, 120)) + if r := decodeGRPCRows(t, drainNow(b))[0]; r.Timestamp != end.UnixMilli() { + t.Fatalf("timestamp = %d, want %d", r.Timestamp, end.UnixMilli()) + } +} + +func TestGRPC_StatusNamesAndErrorCount(t *testing.T) { + reg := metrics.NewRegistry() + b := newGRPCBuffer(t, 0) + for _, code := range []string{"14", "4", "16", "17"} { + b.add(mkSample(reg, grpcCall, callTags(map[string]string{"status": code}), time.Now(), 5)) + } + got := grpcByKey(decodeGRPCRows(t, drainNow(b))) + for code, want := range map[string]string{"14": "UNAVAILABLE", "4": "DEADLINE_EXCEEDED", "16": "UNAUTHENTICATED", "17": "17"} { + r := got["/shop.Cart/Add|"+code] + if r.StatusMessage != want || r.ErrorCount != 1 { + t.Errorf("status %s = %q err=%d, want %s 1", code, r.StatusMessage, r.ErrorCount, want) + } + } +} + +func TestGRPC_StatusMessage(t *testing.T) { + cases := map[string]string{ + "0": "OK", "1": "CANCELLED", "2": "UNKNOWN", "12": "UNIMPLEMENTED", "16": "UNAUTHENTICATED", + "17": "17", "-1": "-1", "01": "01", "NO_STATUS": "NO_STATUS", "": "", + } + for code, want := range cases { + if got := grpcStatusMessage(code); got != want { + t.Errorf("grpcStatusMessage(%q) = %q, want %q", code, got, want) + } + } +} + +func TestGRPC_MissingStatusIsNoStatusError(t *testing.T) { + b := newGRPCBuffer(t, 0) + b.add(mkSample(metrics.NewRegistry(), grpcCall, callTags(map[string]string{"status": ""}), time.Now(), 5)) + rows := decodeGRPCRows(t, drainNow(b)) + if len(rows) != 1 || rows[0].Status != "NO_STATUS" || rows[0].StatusMessage != "NO_STATUS" || rows[0].ErrorCount != 1 { + t.Fatalf("rows = %+v, want one NO_STATUS error row", rows) + } +} + +func TestGRPC_RowName(t *testing.T) { + g := &grpcEngine{reflectionName: reflectionName} + cases := []struct { + desc string + tags map[string]string + want string + }{ + {"name tag wins", map[string]string{"name": "place order", "service": "s.S", "method": "M", "url": "h:1/s.S/M"}, "place order"}, + {"service and method", map[string]string{"service": "hello.HelloService", "method": "SayHello", "url": "h:1/x"}, "/hello.HelloService/SayHello"}, + {"service without method uses url", map[string]string{"service": "hello.HelloService", "url": "h:1/hello.HelloService/SayHello"}, "/hello.HelloService/SayHello"}, + {"url path", map[string]string{"url": "host:9001/hello.HelloService/SayHello"}, "/hello.HelloService/SayHello"}, + {"url without a path", map[string]string{"url": "host:9001"}, "host:9001"}, + {"reflection call", map[string]string{"status": "12"}, reflectionName}, + } + for _, c := range cases { + if got := g.rowName(c.tags); got != c.want { + t.Errorf("%s: rowName = %q, want %q", c.desc, got, c.want) + } + } +} + +func TestGRPC_ReflectionRow(t *testing.T) { + b := newGRPCBuffer(t, 0) + b.add(mkSample(metrics.NewRegistry(), grpcCall, map[string]string{"vu": "1", "scenario": "default", "status": "12"}, time.Now(), 3)) + rows := decodeGRPCRows(t, drainNow(b)) + if len(rows) != 1 || rows[0].RequestName != reflectionName || rows[0].URL != "" { + t.Fatalf("rows = %+v, want the reflection row with an empty url", rows) + } + if rows[0].StatusMessage != "UNIMPLEMENTED" || rows[0].ErrorCount != 1 { + t.Errorf("reflection status = %q err=%d", rows[0].StatusMessage, rows[0].ErrorCount) + } +} + +func TestGRPC_ReflectionNameIsConfigurable(t *testing.T) { + cfg := testSinkConfig() + withGRPC(cfg) + cfg.Correlation.GRPCReflectionName = "reflect" + if err := cfg.Validate(); err != nil { + t.Fatal(err) + } + b := newMetricBuffer(newRowEngine(cfg), 0, time.Minute) + reg := metrics.NewRegistry() + b.add(mkSample(reg, grpcCall, map[string]string{"status": "12"}, time.Now(), 3)) + b.add(mkSample(reg, grpcCall, map[string]string{"status": "1"}, time.Now(), 3)) + rows := decodeGRPCRows(t, drainNow(b)) + if len(rows) != 1 || rows[0].RequestName != "reflect" || rows[0].Status != "12" { + t.Fatalf("rows = %+v, want one row named reflect, status 12", rows) + } +} + +// The reflection call ending CANCELLED forms no row: k6 cancels the reflection +// stream when connect() returns, and native k6 reports no sample for it. +func TestGRPC_ReflectionCancelledFormsNoRow(t *testing.T) { + b := newGRPCBuffer(t, 0) + b.add(mkSample(metrics.NewRegistry(), grpcCall, map[string]string{"vu": "1", "scenario": "default", "status": "1"}, time.Now(), 390)) + if rows := drainNow(b); len(rows) != 0 { + t.Fatalf("rows = %s, want none", rows) + } + if p := b.pending(); p != 0 { + t.Fatalf("pending = %d, want 0", p) + } +} + +// A failed lookup ends UNIMPLEMENTED, then the same connect() cancels the +// stream: exactly one error row, never an error plus an OK. +func TestGRPC_FailedReflectionLookupCountsOnce(t *testing.T) { + reg := metrics.NewRegistry() + b := newGRPCBuffer(t, 0) + at := time.Now() + b.add(mkSample(reg, grpcCall, map[string]string{"scenario": "default", "status": "12"}, at, 3)) + b.add(mkSample(reg, grpcCall, map[string]string{"scenario": "default", "status": "1"}, at.Add(time.Millisecond), 4)) + rows := decodeGRPCRows(t, drainNow(b)) + if len(rows) != 1 { + t.Fatalf("rows = %+v, want exactly one", rows) + } + if r := rows[0]; r.RequestName != reflectionName || r.Status != "12" || r.StatusMessage != "UNIMPLEMENTED" || r.ErrorCount != 1 { + t.Errorf("row = %+v, want one UNIMPLEMENTED reflection error row", r) + } +} + +// Only the reflection call's CANCELLED is dropped: a named call ending +// CANCELLED stays an error, and every other reflection status is written. +func TestGRPC_CancelledOutsideReflectionStaysError(t *testing.T) { + reg := metrics.NewRegistry() + b := newGRPCBuffer(t, 0) + b.add(mkSample(reg, grpcCall, callTags(map[string]string{"status": "1"}), time.Now(), 5)) + for _, code := range []string{"14", "4", "16"} { + b.add(mkSample(reg, grpcCall, map[string]string{"vu": "1", "status": code}, time.Now(), 5)) + } + b.add(mkSample(reg, grpcCall, map[string]string{"vu": "1"}, time.Now(), 5)) + got := grpcByKey(decodeGRPCRows(t, drainNow(b))) + if len(got) != 5 { + t.Fatalf("rows = %v, want 5", got) + } + if r := got["/shop.Cart/Add|1"]; r.StatusMessage != "CANCELLED" || r.ErrorCount != 1 { + t.Errorf("named CANCELLED call = %q err=%d, want CANCELLED 1", r.StatusMessage, r.ErrorCount) + } + for _, code := range []string{"14", "4", "16", "NO_STATUS"} { + if r := got[reflectionName+"|"+code]; r.ErrorCount != 1 { + t.Errorf("reflection status %s = %+v, want an error row", code, r) + } + } +} + +func TestGRPC_DropsCall(t *testing.T) { + g := &grpcEngine{callMetric: grpcCall, reflectionName: reflectionName} + cases := []struct { + desc string + metric string + tags map[string]string + want bool + }{ + {"reflection CANCELLED", grpcCall, map[string]string{"scenario": "default", "status": "1"}, true}, + {"reflection UNIMPLEMENTED", grpcCall, map[string]string{"status": "12"}, false}, + {"reflection DEADLINE_EXCEEDED", grpcCall, map[string]string{"status": "4"}, false}, + {"reflection without status", grpcCall, map[string]string{}, false}, + {"named call CANCELLED", grpcCall, map[string]string{"name": "/a.B/C", "status": "1"}, false}, + {"not the call metric", grpcStreams, map[string]string{"status": "1"}, false}, + } + for _, c := range cases { + if got := g.dropsCall(c.metric, c.tags); got != c.want { + t.Errorf("%s: dropsCall = %v, want %v", c.desc, got, c.want) + } + } + var off *grpcEngine + if off.dropsCall(grpcCall, map[string]string{"status": "1"}) || off.isRowMetric(grpcCall) || off.isCall(grpcCall) { + t.Error("an unconfigured engine must match nothing") + } +} + +// ---- Stream rows ---- + +func TestGRPC_StreamCountersSumPerKey(t *testing.T) { + reg := metrics.NewRegistry() + b := newGRPCBuffer(t, 0) + tags := callTags(map[string]string{"name": "/chat.Room/Talk", "status": ""}) + now := time.Unix(1_700_000_001, 0) + b.add(mkSample(reg, grpcStreams, tags, now, 1)) + b.add(mkSample(reg, grpcStreams, tags, now, 1)) + for i := 0; i < 5; i++ { + b.add(mkSample(reg, grpcMsgsSent, tags, now, 1)) + } + for i := 0; i < 7; i++ { + b.add(mkSample(reg, grpcMsgsReceived, tags, now, 1)) + } + b.add(mkSample(reg, grpcStreams, callTags(map[string]string{"name": "/chat.Room/Listen"}), now, 1)) + + raw := drainNow(b) + rows := decodeGRPCRows(t, raw) + if len(rows) != 2 { + t.Fatalf("rows = %d, want 2 (one per row name)", len(rows)) + } + by := map[string]grpcRow{} + for _, r := range rows { + by[r.RequestName] = r + } + talk := by["/chat.Room/Talk"] + if talk.Protocol != "grpc_stream" || talk.StreamsOpened != 2 || talk.MsgsSent != 5 || talk.MsgsReceived != 7 { + t.Errorf("talk = %+v", talk) + } + if talk.Status != "" || talk.StatusMessage != "" || talk.Duration != 0 || talk.ErrorCount != 0 { + t.Errorf("stream row status/message/duration/err = %q/%q/%d/%d, want empty/empty/0/0", + talk.Status, talk.StatusMessage, talk.Duration, talk.ErrorCount) + } + if talk.Timestamp != now.UnixMilli() || talk.URL != "cart:50051/shop.Cart/Add" || talk.Group != "::checkout" { + t.Errorf("talk timestamp/url/group = %d/%q/%q", talk.Timestamp, talk.URL, talk.Group) + } + if listen := by["/chat.Room/Listen"]; listen.StreamsOpened != 1 || listen.MsgsSent != 0 { + t.Errorf("listen = %+v", listen) + } + // A zero counter is left out, like on HTTP rows. + for _, r := range raw { + if strings.Contains(string(r), `"/chat.Room/Listen"`) && strings.Contains(string(r), `"msgsSent"`) { + t.Errorf("a zero counter was written: %s", r) + } + } + if again := drainNow(b); len(again) != 0 { + t.Errorf("second drain = %d rows, want 0 (counters reset per flush)", len(again)) + } +} + +// A flush that crosses a bucket boundary keeps each bucket's counters apart. +func TestGRPC_StreamCountersSplitAtBucketBoundary(t *testing.T) { + reg := metrics.NewRegistry() + b := newGRPCBuffer(t, 0) + tags := callTags(map[string]string{"name": "/chat.Room/Talk", "status": ""}) + first, second := time.Unix(1_700_000_008, 0), time.Unix(1_700_000_011, 0) + b.add(mkSample(reg, grpcMsgsSent, tags, first, 1)) + b.add(mkSample(reg, grpcMsgsSent, tags, first.Add(time.Second), 1)) + b.add(mkSample(reg, grpcMsgsSent, tags, second, 1)) + + sent := map[int64]int64{} + for _, r := range decodeGRPCRows(t, drainNow(b)) { + sent[r.Timestamp] = r.MsgsSent + } + if len(sent) != 2 || sent[first.UnixMilli()] != 2 || sent[second.UnixMilli()] != 1 { + t.Errorf("msgsSent by row timestamp = %v, want {%d:2, %d:1}", sent, first.UnixMilli(), second.UnixMilli()) + } +} + +func TestGRPC_StreamBucketIsConfigurable(t *testing.T) { + cfg := testSinkConfig() + withGRPC(cfg) + cfg.Correlation.GRPCStreamBucket = Duration(time.Minute) + if err := cfg.Validate(); err != nil { + t.Fatal(err) + } + b := newMetricBuffer(newRowEngine(cfg), 0, time.Minute) + reg := metrics.NewRegistry() + tags := callTags(map[string]string{"status": ""}) + b.add(mkSample(reg, grpcMsgsSent, tags, time.Unix(1_700_000_008, 0), 1)) + b.add(mkSample(reg, grpcMsgsSent, tags, time.Unix(1_700_000_011, 0), 1)) + if rows := decodeGRPCRows(t, drainNow(b)); len(rows) != 1 || rows[0].MsgsSent != 2 { + t.Fatalf("rows = %+v, want one row summing 2", rows) + } +} + +// Samples that differ on a tag a column reads sum into separate rows, so a +// summed row never mixes two values of that column. +func TestGRPC_StreamKeyIncludesColumnTags(t *testing.T) { + reg := metrics.NewRegistry() + b := newGRPCBuffer(t, 0) + at := time.Unix(1_700_000_001, 0) + b.add(mkSample(reg, grpcStreams, callTags(map[string]string{"instance": "a"}), at, 1)) + b.add(mkSample(reg, grpcStreams, callTags(map[string]string{"instance": "b"}), at, 1)) + b.add(mkSample(reg, grpcStreams, callTags(map[string]string{"instance": "b", "vu": "9"}), at, 1)) + got := map[string]int64{} + for _, r := range decodeGRPCRows(t, drainNow(b)) { + got[r.Instance] = r.StreamsOpened + } + if len(got) != 2 || got["a"] != 1 || got["b"] != 2 { + t.Fatalf("streamsOpened by instance = %v, want {a:1, b:2}", got) + } +} + +func TestGRPC_OnlyConfiguredStreamCountersFormRows(t *testing.T) { + cfg := testSinkConfig() + cfg.Correlation.GRPCStreamMetrics = &GRPCStreamMetrics{MsgsSent: grpcMsgsSent} + cfg.Columns = append(cfg.Columns, mustColumns(grpcColumnsJSON)...) + if err := cfg.Validate(); err != nil { + t.Fatal(err) + } + b := newMetricBuffer(newRowEngine(cfg), 0, time.Minute) + reg := metrics.NewRegistry() + b.add(mkSample(reg, grpcCall, callTags(nil), time.Now(), 5)) + b.add(mkSample(reg, grpcStreams, callTags(nil), time.Now(), 1)) + b.add(mkSample(reg, grpcMsgsSent, callTags(nil), time.Now(), 3)) + rows := decodeGRPCRows(t, drainNow(b)) + if len(rows) != 1 || rows[0].Protocol != "grpc_stream" || rows[0].MsgsSent != 3 || rows[0].StreamsOpened != 0 { + t.Fatalf("rows = %+v, want one stream row with msgsSent 3", rows) + } +} + +// ---- Buffering ---- + +// gRPC rows are complete on arrival, so they leave on every tick, even one +// that holds back request rows still settling. +func TestGRPC_DrainsOnEveryTick(t *testing.T) { + reg := metrics.NewRegistry() + b := newGRPCBuffer(t, 0) + b.add(mkSample(reg, "http_reqs", reqTags("1"), time.Now(), 1)) + b.add(mkSample(reg, grpcCall, callTags(nil), time.Now(), 5)) + b.add(mkSample(reg, grpcStreams, callTags(nil), time.Now(), 1)) + rows := decodeGRPCRows(t, b.drainReady(time.Now().Add(-time.Hour))) + if len(rows) != 2 || rows[0].Protocol == "" || rows[1].Protocol == "" { + t.Fatalf("rows = %+v, want the two gRPC rows only", rows) + } + if p := b.pending(); p != 1 { + t.Fatalf("pending = %d, want 1 (the request)", p) + } +} + +func TestGRPC_DrainAllAndPending(t *testing.T) { + reg := metrics.NewRegistry() + b := newGRPCBuffer(t, 0) + b.add(mkSample(reg, grpcCall, callTags(nil), time.Now(), 5)) + b.add(mkSample(reg, grpcStreams, callTags(nil), time.Now(), 1)) + b.add(mkSample(reg, grpcMsgsSent, callTags(nil), time.Now(), 1)) + if p := b.pending(); p != 2 { + t.Errorf("pending = %d, want 2", p) + } + if rows := b.drainAll(); len(rows) != 2 { + t.Errorf("drainAll = %d rows, want 2", len(rows)) + } + if p := b.pending(); p != 0 { + t.Errorf("pending after drain = %d, want 0", p) + } +} + +func TestGRPC_CapShedsNewRows(t *testing.T) { + reg := metrics.NewRegistry() + b := newGRPCBuffer(t, 1) + b.add(mkSample(reg, grpcCall, callTags(nil), time.Now(), 5)) + b.add(mkSample(reg, grpcCall, callTags(nil), time.Now(), 5)) + at := time.Unix(1_700_000_001, 0) + b.add(mkSample(reg, grpcStreams, callTags(nil), at, 1)) + b.add(mkSample(reg, grpcStreams, callTags(nil), at, 1)) // same key: summed + b.add(mkSample(reg, grpcStreams, callTags(map[string]string{"name": "/other.S/M"}), at, 1)) // new key: shed + if d := b.droppedCount(); d != 2 { + t.Errorf("dropped = %d, want 2", d) + } + rows := decodeGRPCRows(t, b.drainAll()) + if len(rows) != 2 { + t.Fatalf("rows = %d, want 2", len(rows)) + } +} + +// With no gRPC configuration gRPC samples form no rows, as before. +func TestGRPC_UnconfiguredFormsNoRows(t *testing.T) { + reg := metrics.NewRegistry() + b := newTestBuffer(t, 0) + for _, name := range []string{grpcCall, grpcStreams, grpcMsgsSent, grpcMsgsReceived} { + b.add(mkSample(reg, name, callTags(nil), time.Now(), 5)) + } + if rows := b.drainAll(); len(rows) != 0 { + t.Errorf("rows = %s, want none", rows) + } + if p := b.pending(); p != 0 { + t.Errorf("pending = %d, want 0", p) + } +} + +// A script's own metric starting with grpc_ is not a gRPC row metric. +func TestGRPC_CustomGRPCPrefixedMetricIgnored(t *testing.T) { + b := newGRPCBuffer(t, 0) + b.add(mkSample(metrics.NewRegistry(), "grpc_custom_latency", callTags(nil), time.Now(), 5)) + if rows := drainNow(b); len(rows) != 0 { + t.Errorf("rows = %s, want none", rows) + } +} + +// ---- HTTP and WebSocket rows are unchanged with the gRPC configuration set ---- + +const ( + goldenGRPCCallRow = `{"timestamp":1699999999988,"job":"job-const","scenario":"default","status":"0","statusMessage":"OK",` + + `"url":"cart:50051/shop.Cart/Add","requestName":"/shop.Cart/Add","group":"::checkout","vus":3,"bytesReceived":0,"bytesSent":0,` + + `"latency":0,"connect":0,"duration":12,"errorCount":0,"instance":"main","protocol":"grpc"}` + goldenGRPCStreamRow = `{"timestamp":1700000000000,"job":"job-const","scenario":"default","status":"","statusMessage":"",` + + `"url":"cart:50051/shop.Cart/Add","requestName":"/shop.Cart/Add","group":"::checkout","vus":3,"bytesReceived":0,"bytesSent":0,` + + `"latency":0,"connect":0,"duration":0,"errorCount":0,"instance":"main","protocol":"grpc_stream","streamsOpened":1,"msgsSent":2}` +) + +func grpcFeatureSamples(reg *metrics.Registry) []metrics.Sample { + at := time.UnixMilli(1_700_000_000_000) + stream := callTags(map[string]string{"status": ""}) + return append(featureSamples(reg), + mkSample(reg, grpcCall, callTags(nil), at, 12), + mkSample(reg, grpcCall, map[string]string{"status": "1"}, at, 4), // dropped + mkSample(reg, grpcStreams, stream, at, 1), + mkSample(reg, grpcMsgsSent, stream, at, 2), + ) +} + +func TestGRPC_ConfiguredBufferKeepsHTTPAndWSRowsByteIdentical(t *testing.T) { + reg := metrics.NewRegistry() + b := newConfiguredBuffer(t, withGRPC) + for _, s := range grpcFeatureSamples(reg) { + b.add(s) + } + got := map[string]bool{} + for _, r := range drainNow(b) { + got[string(r)] = true + } + for _, want := range []string{goldenRequestRow, goldenWSRow, goldenGRPCCallRow, goldenGRPCStreamRow} { + if !got[want] { + t.Errorf("missing row\n%s\nin\n%v", want, sortedRows(got)) + } + } + if len(got) != 4 { + t.Errorf("rows = %d, want 4:\n%v", len(got), sortedRows(got)) + } +} + +func TestGRPC_ConfiguredSinkKeepsHTTPAndWSPayloadsByteIdentical(t *testing.T) { + rec := newRecorder(t) + s, _ := testSink(t, rec.srv.URL, withGRPC) + if err := s.Start(); err != nil { + t.Fatal(err) + } + s.AddMetricSamples(samples(grpcFeatureSamples(metrics.NewRegistry())...)) + if err := s.Stop(); err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimSuffix(strings.Join(rec.bodies["requests"], ""), "\n"), "\n") + want := []string{goldenRequestRow, goldenGRPCCallRow, goldenGRPCStreamRow, goldenWSRow} + sort.Strings(lines) + sort.Strings(want) + if strings.Join(lines, "\n") != strings.Join(want, "\n") { + t.Fatalf("request payload =\n%s\nwant\n%s", strings.Join(lines, "\n"), strings.Join(want, "\n")) + } + if got, want := strings.Join(rec.bodies["checks"], ""), goldenCheckRow+"\n"; got != want { + t.Fatalf("check payload =\n%s\nwant\n%s", got, want) + } +} + +func sortedRows(set map[string]bool) []string { + out := make([]string, 0, len(set)) + for r := range set { + out = append(out, r) + } + sort.Strings(out) + return out +} + +// ---- Data marker and check correlation ---- + +func TestGRPC_DataMarker(t *testing.T) { + cases := []struct { + desc string + mutate func(*Config) + metric string + tags map[string]string + want bool + }{ + {"call", withGRPC, grpcCall, callTags(nil), true}, + {"stream counter", withGRPC, grpcStreams, callTags(nil), true}, + {"reflection CANCELLED", withGRPC, grpcCall, map[string]string{"vu": "1", "status": "1"}, false}, + {"reflection UNIMPLEMENTED", withGRPC, grpcCall, map[string]string{"vu": "1", "status": "12"}, true}, + {"custom grpc_ metric", withGRPC, "grpc_custom_latency", callTags(nil), false}, + {"unconfigured", nil, grpcCall, callTags(nil), false}, + } + for _, c := range cases { + t.Run(c.desc, func(t *testing.T) { + s, dir := testSink(t, "http://127.0.0.1:1", c.mutate) + s.AddMetricSamples(samples(mkSample(metrics.NewRegistry(), c.metric, c.tags, time.Unix(1700000000, 0), 1))) + if got := exists(filepath.Join(dir, "data")); got != c.want { + t.Fatalf("script data marked = %v, want %v", got, c.want) + } + }) + } +} + +// Even a data prefix covering grpc_ does not let the dropped sample mark data. +func TestGRPC_DroppedSampleNeverMarksData(t *testing.T) { + s, dir := testSink(t, "http://127.0.0.1:1", func(c *Config) { + withGRPC(c) + c.Markers.DataMetricPrefixes = append(c.Markers.DataMetricPrefixes, "grpc_") + }) + s.AddMetricSamples(samples(mkSample(metrics.NewRegistry(), grpcCall, map[string]string{"status": "1"}, time.Unix(1700000000, 0), 1))) + if exists(filepath.Join(dir, "data")) { + t.Fatal("the reflection call's CANCELLED marked script data") + } +} + +// checkFeed pushes samples one at a time, each a millisecond after the last. +type checkFeed struct { + t *testing.T + s *sink + reg *metrics.Registry + at time.Time +} + +func newCheckFeed(t *testing.T, mutate func(*Config)) *checkFeed { + s, _ := testSink(t, "http://127.0.0.1:1", mutate) + return &checkFeed{t: t, s: s, reg: metrics.NewRegistry(), at: time.Unix(1700000000, 0)} +} + +func (f *checkFeed) push(name string, tags map[string]string) { + f.at = f.at.Add(time.Millisecond) + f.s.AddMetricSamples(samples(mkSample(f.reg, name, tags, f.at, 12))) +} + +func (f *checkFeed) http(vu, name, status string) { + f.push("http_reqs", map[string]string{"vu": vu, "method": "GET", "name": name, "status": status}) +} + +func (f *checkFeed) call(vu string, tags map[string]string) { + merged := map[string]string{"vu": vu} + for k, v := range tags { + merged[k] = v + } + f.push(grpcCall, merged) +} + +func (f *checkFeed) check(vu, name string) { + f.push("checks", map[string]string{"vu": vu, "check": name}) +} + +// labels returns "check=label/status" for every check row, in order. +func (f *checkFeed) labels() string { + var out []string + for _, a := range decodeAssertions(f.t, f.s.assertions.drain()) { + out = append(out, a.Name+"="+a.Label+"/"+a.Status) + } + return strings.Join(out, " ") +} + +var sayHello = map[string]string{ + "name": "/hello.HelloService/SayHello", "service": "hello.HelloService", "method": "SayHello", + "url": "grpcbin.example:9001/hello.HelloService/SayHello", "status": "0", +} + +func TestGRPC_CheckCorrelation(t *testing.T) { + cases := []struct { + desc string + feed func(f *checkFeed) + want string + }{ + {"gRPC call after HTTP", func(f *checkFeed) { + f.http("1", "GET /orders", "200") + f.call("1", sayHello) + f.check("1", "ok") + }, "ok=/hello.HelloService/SayHello/0"}, + {"custom name and error status", func(f *checkFeed) { + f.call("1", map[string]string{"name": "place order", "service": "shop.Orders", "method": "Place", "status": "14"}) + f.check("1", "ok") + }, "ok=place order/14"}, + {"no status uses the sentinel", func(f *checkFeed) { + f.http("1", "GET /orders", "200") + f.call("1", map[string]string{"name": "/hello.HelloService/SayHello"}) + f.check("1", "ok") + }, "ok=/hello.HelloService/SayHello/NO_STATUS"}, + {"interleaved VUs", func(f *checkFeed) { + f.http("1", "GET /orders", "200") + f.call("2", sayHello) + f.check("1", "a") + f.check("2", "b") + f.call("1", map[string]string{"name": "place order", "status": "3"}) + f.http("2", "GET /cart", "404") + f.check("2", "c") + f.check("1", "d") + }, "a=GET /orders/200 b=/hello.HelloService/SayHello/0 c=GET /cart/404 d=place order/3"}, + {"stream counters do not relabel; the stream's end does", func(f *checkFeed) { + f.http("1", "GET /before", "200") + f.push(grpcStreams, map[string]string{"vu": "1", "name": "/route.Guide/RouteChat"}) + f.check("1", "a") + f.call("1", map[string]string{"name": "/route.Guide/RouteChat", "status": "0"}) + f.check("1", "b") + f.http("1", "GET /after", "200") + f.check("1", "c") + }, "a=GET /before/200 b=/route.Guide/RouteChat/0 c=GET /after/200"}, + {"reflection CANCELLED labels nothing", func(f *checkFeed) { + f.call("1", sayHello) + f.call("1", map[string]string{"status": "1"}) + f.check("1", "a") + }, "a=/hello.HelloService/SayHello/0"}, + {"failed reflection then check", func(f *checkFeed) { + f.call("1", map[string]string{"status": "12"}) + f.call("1", map[string]string{"status": "1"}) + f.check("1", "a") + }, "a=" + reflectionName + "/12"}, + {"no vu tag leaves checks unlabelled", func(f *checkFeed) { + f.push("http_reqs", map[string]string{"name": "GET /orders", "status": "200"}) + f.push(grpcCall, sayHello) + f.push("checks", map[string]string{"check": "a"}) + }, "a=/"}, + } + for _, c := range cases { + t.Run(c.desc, func(t *testing.T) { + f := newCheckFeed(t, withGRPC) + c.feed(f) + if got := f.labels(); got != c.want { + t.Fatalf("checks = %q, want %q", got, c.want) + } + }) + } +} + +func TestGRPC_UnconfiguredLeavesCheckCorrelationAlone(t *testing.T) { + f := newCheckFeed(t, nil) + f.http("1", "GET /orders", "200") + f.call("1", sayHello) + f.check("1", "ok") + if got := f.labels(); got != "ok=GET /orders/200" { + t.Fatalf("checks = %q, want the HTTP request's label", got) + } +} + +// ---- Configuration ---- + +func TestGRPC_ConfigIsValidated(t *testing.T) { + cases := map[string]struct { + mutate func(*Config) + want string + }{ + "call is a request metric": {func(c *Config) { c.Correlation.GRPCCallMetric = "http_reqs" }, "grpcCallMetric"}, + "call is the check metric": {func(c *Config) { c.Correlation.GRPCCallMetric = "checks" }, "the check metric"}, + "stream is a WebSocket metric": {func(c *Config) { + c.Correlation.GRPCStreamMetrics = &GRPCStreamMetrics{MsgsSent: "ws_msgs_sent"} + }, "WebSocket"}, + "stream equals call": {func(c *Config) { + c.Correlation.GRPCCallMetric = grpcCall + c.Correlation.GRPCStreamMetrics = &GRPCStreamMetrics{StreamsOpened: grpcCall} + }, "the gRPC call metric"}, + "duplicate stream metric": {func(c *Config) { + c.Correlation.GRPCStreamMetrics = &GRPCStreamMetrics{MsgsSent: "m", MsgsReceived: "m"} + }, "a gRPC stream metric"}, + "empty stream metrics": {func(c *Config) { c.Correlation.GRPCStreamMetrics = &GRPCStreamMetrics{} }, "at least one"}, + "reflection name without call": {func(c *Config) { + c.Correlation.GRPCStreamMetrics = &GRPCStreamMetrics{StreamsOpened: grpcStreams} + c.Correlation.GRPCReflectionName = "r" + }, "grpcReflectionName"}, + "bucket without streams": {func(c *Config) { + c.Correlation.GRPCCallMetric = grpcCall + c.Correlation.GRPCStreamBucket = Duration(time.Second) + }, "grpcStreamBucket"}, + "protocol without gRPC": {func(c *Config) { + c.Columns = append(c.Columns, mustColumns(`[{"name":"p","from":"computed:protocol"}]`)...) + }, "computed:protocol requires"}, + "stream counter without streams": {func(c *Config) { + c.Correlation.GRPCCallMetric = grpcCall + c.Columns = append(c.Columns, mustColumns(`[{"name":"s","from":"computed:msgsSent"}]`)...) + }, "computed:msgsSent requires sink.correlation.grpcStreamMetrics"}, + "stream counter on checks": {func(c *Config) { + withGRPC(c) + c.AssertionColumns = append(c.AssertionColumns, mustColumns(`[{"name":"s","from":"computed:msgsSent"}]`)...) + }, "unknown computed"}, + "verdict is the call metric": {func(c *Config) { + withGRPC(c) + c.Correlation.VerdictMetric = grpcCall + }, "the gRPC call metric"}, + "join is a stream metric": {func(c *Config) { + withGRPC(c) + c.Correlation.JoinMetrics = []string{grpcStreams} + }, "a gRPC stream metric"}, + "seen is the call metric": {func(c *Config) { + withGRPC(c) + c.Summary = baseSummary(filepath.Join(string(filepath.Separator), "tmp", "summary")) + c.Summary.Keys.Seen = map[string]string{"x": grpcCall} + }, "never becomes a row"}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + cfg := testSinkConfig() + tc.mutate(cfg) + if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("err = %v, want it to mention %q", err, tc.want) + } + }) + } + cfg := testSinkConfig() + withGRPC(cfg) + cfg.Correlation.GRPCReflectionName = "r" + cfg.Correlation.GRPCStreamBucket = Duration(5 * time.Second) + if err := cfg.Validate(); err != nil { + t.Fatalf("full gRPC configuration rejected: %v", err) + } +} + +func TestGRPC_ConfigDecodesStrictly(t *testing.T) { + var c CorrelationConfig + dec := json.NewDecoder(strings.NewReader(`{"grpcStreamMetrics": {"streamsOpened": "a", "streams": "b"}}`)) + dec.DisallowUnknownFields() + if err := dec.Decode(&c); err == nil || !strings.Contains(err.Error(), "unknown field") { + t.Fatalf("err = %v, want an unknown field error", err) + } + dec = json.NewDecoder(strings.NewReader(`{"grpcStreamBucket": "soon"}`)) + if err := dec.Decode(&c); err == nil || !strings.Contains(err.Error(), "duration") { + t.Fatalf("err = %v, want a duration error", err) + } +} + +// omitEmpty leaves an empty column out; without it the column is always written. +func TestColumn_OmitEmpty(t *testing.T) { + cols, err := compileColumns(mustColumns(`[ + {"name":"a","from":"tag:a","omitEmpty":true}, + {"name":"b","from":"tag:b"}, + {"name":"n","from":"computed:duration","omitEmpty":true}, + {"name":"u","from":"tag:u","type":"uint","max":9,"omitEmpty":true} + ]`), requestBuiltins, nil, "c") + if err != nil { + t.Fatal(err) + } + cases := []struct { + tags map[string]string + duration int64 + want string + }{ + {map[string]string{}, 0, `{"b":""}`}, + {map[string]string{"a": "x", "u": "3"}, 5, `{"a":"x","b":"","n":5,"u":3}`}, + {map[string]string{"b": "y", "u": "99"}, 0, `{"b":"y"}`}, + } + for _, c := range cases { + v := rowView{tags: c.tags, duration: c.duration} + if got := string(cols.appendRow(nil, &v)); got != c.want { + t.Errorf("row = %s, want %s", got, c.want) + } + } + only, _ := compileColumns(mustColumns(`[{"name":"a","from":"tag:a","omitEmpty":true}]`), requestBuiltins, nil, "c") + if got := string(only.appendRow(nil, &rowView{tags: map[string]string{}})); got != `{}` { + t.Errorf("all-omitted row = %s, want {}", got) + } +} diff --git a/internal/sink/sink.go b/internal/sink/sink.go index c190298..15754be 100644 --- a/internal/sink/sink.go +++ b/internal/sink/sink.go @@ -53,8 +53,8 @@ const ( httpReqsMetric = "http_reqs" ) -// vuReqContext holds one VU's most recent request label and status, so a check -// sample can be attributed to the request it followed. +// vuReqContext holds one VU's most recent request (or gRPC call) label and +// status, so a check sample can be attributed to the request it followed. type vuReqContext struct { label string status string @@ -391,6 +391,9 @@ func (s *sink) isDataMetric(name string) bool { if name == s.cfg.Correlation.CheckMetric && name != "" { return true } + if s.buffer.engine.grpc.isRowMetric(name) { + return true + } for _, prefix := range s.dataPrefixes { if strings.HasPrefix(name, prefix) { return true @@ -401,6 +404,7 @@ func (s *sink) isDataMetric(name string) bool { func (s *sink) AddMetricSamples(sampleContainers []metrics.SampleContainer) { checkMetric := s.cfg.Correlation.CheckMetric + grpc := s.buffer.engine.grpc for _, container := range sampleContainers { for _, sample := range container.GetSamples() { // Every sample but an exempt metric's counts against the budget; @@ -418,6 +422,11 @@ func (s *sink) AddMetricSamples(sampleContainers []metrics.SampleContainer) { continue } tags := extractTags(sample) + // The reflection call's CANCELLED is not a call: it forms no row, + // marks no data and labels no check. + if grpc.dropsCall(metricName, tags) { + continue + } // An absent group key is not the same as an empty one. groupTag, hasGroupTag := tags["group"] @@ -447,6 +456,13 @@ func (s *sink) AddMetricSamples(sampleContainers []metrics.SampleContainer) { ctx.status = status } } + // A finished gRPC call is the VU's last call too, so a check after it + // is attributed to the gRPC row. + if vuID != "" && grpc.isCall(metricName) { + ctx := s.getVUContext(vuID) + ctx.label = grpc.rowName(tags) + ctx.status = grpcStatusCode(tags) + } if checkMetric != "" && metricName == checkMetric { if !s.assertions.enabled() { From 1fba55baceaa0f64df474fcc116b58decf4ac67b Mon Sep 17 00:00:00 2001 From: Dheeren Date: Tue, 1 Dec 2026 13:19:23 +0530 Subject: [PATCH 02/11] gRPC capture and pacing through k6 gRPC hooks; k6 patch support in build.sh and the release gate --- .github/workflows/ci.yml | 27 +- README.md | 75 ++++- SOURCE.md | 25 +- build.sh | 56 +++- extensions.json | 4 + go.mod | 1 + internal/config/config.go | 16 + internal/grpccapture/capture.go | 346 +++++++++++++++++++++ internal/grpccapture/capture_test.go | 413 +++++++++++++++++++++++++ internal/grpccapture/config.go | 164 ++++++++++ internal/grpccapture/hook.go | 33 ++ internal/grpccapture/hook_stock.go | 10 + internal/throughput/grpc.go | 25 ++ internal/throughput/grpc_hook.go | 9 + internal/throughput/grpc_hook_stock.go | 6 + internal/throughput/grpc_test.go | 96 ++++++ internal/throughput/module.go | 14 +- patches/k6-grpc-capture.patch | 195 ++++++++++++ patches/k6-grpc-deadline.patch | 59 ++++ register.go | 27 +- scripts/check-source-md.sh | 13 +- scripts/release-gate.sh | 22 +- scripts/release-gate_test.sh | 8 + 23 files changed, 1613 insertions(+), 31 deletions(-) create mode 100644 internal/grpccapture/capture.go create mode 100644 internal/grpccapture/capture_test.go create mode 100644 internal/grpccapture/config.go create mode 100644 internal/grpccapture/hook.go create mode 100644 internal/grpccapture/hook_stock.go create mode 100644 internal/throughput/grpc.go create mode 100644 internal/throughput/grpc_hook.go create mode 100644 internal/throughput/grpc_hook_stock.go create mode 100644 internal/throughput/grpc_test.go create mode 100644 patches/k6-grpc-capture.patch create mode 100644 patches/k6-grpc-deadline.patch diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e6fdf3f..1199932 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,13 +26,36 @@ jobs: cache: true - name: gofmt run: test -z "$(gofmt -l .)" || { gofmt -l .; exit 1; } + # The gRPC hooks exist only in the patched k6 (see patches/), so the unit + # tests build against stock k6 with -tags stock_k6; the patched-build job + # compiles the hooked code. - name: go vet - run: go vet ./... + run: go vet -tags stock_k6 ./... - name: go test - run: go test -race -count=1 ./... + run: go test -tags stock_k6 -race -count=1 ./... - name: Release gate tests run: bash scripts/release-gate_test.sh - name: SOURCE.md lists the pinned components run: bash scripts/check-source-md.sh - name: Release tag script tests run: bash scripts/tag-release_test.sh + + patched-build: + # Builds the real binary (k6 patches applied, every extension linked) and + # runs the release gate on it, so a patch that no longer applies or hooked + # code that no longer compiles fails the PR. + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false + - uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0 + with: + go-version: "1.26.11" + cache: true + - name: Install xk6 + run: go install go.k6.io/xk6/cmd/xk6@v1.4.12 + - name: Build k6 (linux/amd64) + run: GOOS=linux GOARCH=amd64 CGO_ENABLED=0 ./build.sh --output dist/k6 + - name: Release gate + run: bash scripts/release-gate.sh --binary dist/k6 --arch amd64 diff --git a/README.md b/README.md index b3b0e51..9aaf1b3 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,13 @@ Setting `schedule` together with `podRps` is an error. `_acquireUpTo(n)` takes 1..n grants at one instant and returns how many, so a batch can be sent in slices that each fit the ceiling. +gRPC calls are paced too, with no script change: when the section is present, +the limiter is registered with the k6 gRPC hooks (see [k6 patches](#k6-patches)), +and each unary call and each stream open takes one grant from the same limiter +before it starts, so HTTP and gRPC share one rate. Messages inside a stream take +nothing. The wait runs on the call's own context, so a call whose deadline passes +while it waits fails with `DEADLINE_EXCEEDED` and is recorded as a failed call. + ### `tagFilter` `include` or `exclude` is a JSON string `{"test":[...],"group":[...],"scenario":[...]}`. @@ -84,6 +91,28 @@ group and every nested group (`A` matches `::A::B`). The JS module exports `_mode()`, `_shouldRunRequest(tags)`, `_shouldRunGroup(name)` and `_shouldRunScenario(name)`. +### `grpcCapture` + +Records a bounded sample of the run's gRPC calls (request message and metadata, +response message or error, headers and trailers) as JSON lines in `file`. It +uses the k6 gRPC hooks (see [k6 patches](#k6-patches)), so it sees every call +whatever way the script imports `k6/net/grpc`. + +| Key | Meaning | +|---|---| +| `file` | required: a file the caller created; samples are appended (opened without `O_CREATE` and with `O_NOFOLLOW`) | +| `totalVUs` | the VU ids (1..totalVUs) capturing VUs are chosen from (default 1) | +| `vuSeed` | seed of the shuffle that picks the capturing VUs (truncated to 32 bits) | +| `maxCapturingVUs` | how many VUs capture (default 20) | +| `maxSuccess`, `maxErrors` | distinct successful / failing calls kept | +| `maxErrorsPerScenario` | failing calls kept per scenario (default 13) | +| `exclude` | `[{ "pattern": "...", "regex": false }]`: OK calls never kept, matched on the call name or full method with one leading `/` trimmed | + +One sample is kept per (scenario, call name, status code). Messages are +protojson, cut at 64 KB; each metadata map is cut at 16 KB. A file that cannot +be opened or written turns capture off for the run, with one line on stderr. +Metadata is written as received: redact it before it leaves the machine. + ### `sink` Rows are posted as `JSONEachRow` to a ClickHouse-HTTP-compatible endpoint @@ -247,8 +276,9 @@ ones.) The summary then reads, for example, ## Building k6 with the bundled extensions -`extensions.json` lists the k6 version (`k6Version`), this module (`repoPath: "."`) -and the third-party extensions bundled with it, each pinned to one version. +`extensions.json` lists the k6 version (`k6Version`), the k6 patches +(`k6Patches`), this module (`repoPath: "."`) and the third-party extensions +bundled with it, each pinned to one version. `build.sh` turns it into a static binary with [xk6](https://github.com/grafana/xk6) (needs Go, xk6 and jq): @@ -259,9 +289,35 @@ scripts/release-gate.sh --binary dist/k6-linux-amd64 --arch amd64 `scripts/release-gate.sh` reads the binary's Go build information (`go version -m`) and fails unless it is linux/`` with CGO off, links -`go.k6.io/k6/v2` at `k6Version`, links every pinned extension at exactly its -version (not replaced) and this module, and links no other xk6 module than the -ones k6 itself requires. +`go.k6.io/k6/v2` at `k6Version` (replaced by exactly the patched copy when +`k6Patches` is set), links every pinned extension at exactly its version (not +replaced) and this module, and links no other xk6 module than the ones k6 +itself requires. + +### k6 patches + +`k6Patches` lists patch files under `patches/`. `build.sh` downloads the pinned +k6 source through the Go module proxy, copies it to +`/tmp/xk6-load-toolkit/k6--patched` (a fixed path, because the +directory is recorded in the binary's build info), applies each patch with +`git apply`, and builds with `--replace go.k6.io/k6/v2=`. A patch +that no longer applies fails the build, and so does a binary not linked against +the patched copy. Bumping `k6Version` means re-checking every patch. + +| Patch | Why | +|---|---| +| `k6-grpc-deadline.patch` | stock k6 drops the `grpc_req_duration` sample of a call that ends with `DEADLINE_EXCEEDED` (the deadline cancels the context the sample is pushed with); the patch pushes it against the VU context, so timed-out calls are counted | +| `k6-grpc-capture.patch` | adds `lib/netext/grpccapture`: a hook an extension registers to observe every gRPC call's stats (used by `grpcCapture`) and a pacer called before each unary call and stream open (used by `throughput`) | + +The hooks live in k6's gRPC client rather than in a JavaScript wrapper around +`k6/net/grpc`, because a wrapper only sees calls made through the module's +default export: a script that writes `import { Client } from "k6/net/grpc"`, +`import { Client as C } ...` or `import * as grpc ...` bypasses it, and a wrapper +cannot recover the samples k6 drops for timed-out calls. + +The Go code that uses the hooks (`internal/grpccapture/hook.go`, +`internal/throughput/grpc_hook.go`) builds only against the patched k6; with +`-tags stock_k6` it compiles to no-ops, which is how the unit tests run. ## Distribution @@ -285,12 +341,15 @@ scripts/release-gate.sh --binary dist/k6-linux-amd64 --arch amd64 --manifest ext ``` register.go the only root file: init() registers the output and the two JS - modules with k6; the package exports nothing + modules with k6 and connects the gRPC hooks; the package exports + nothing +patches/ the k6 patches build.sh applies internal/config/ reads the document at init, applies env.unset, strict decode, composes the capability sections and validates each one internal/sink/ the output: buffers, columns, cardinality guard, markers internal/throughput/ the limiter, the schedule and their JS module; testdata/ holds the schedule fixtures and their generator +internal/grpccapture/ the gRPC call capture and its k6-hook adapter (hook.go) internal/tag-filter/ the tag filter, its JS module and the check-sample policy (package tagfilter: Go package names cannot contain '-', so importers use `tagfilter "…/internal/tag-filter"`) @@ -318,8 +377,10 @@ interface; the root package hands it over. ## Tests ```sh -go test ./... +go test -tags stock_k6 ./... # unit tests, against stock k6 scripts/release-gate_test.sh +GOOS=linux GOARCH=amd64 ./build.sh --output dist/k6 && \ + scripts/release-gate.sh --binary dist/k6 --arch amd64 # compiles the hooked code ``` ## License diff --git a/SOURCE.md b/SOURCE.md index 3929007..92baa4c 100644 --- a/SOURCE.md +++ b/SOURCE.md @@ -34,9 +34,21 @@ Read this file at that tag (or commit): | Component | Go module | Version | Commit | Licence | Source | |---|---|---|---|---|---| -| k6 | `go.k6.io/k6/v2` | v2.2.0 | `00a9a1b7f552d6bb4337278b10ae25aac0f4e666` | AGPL-3.0 | | +| k6 | `go.k6.io/k6/v2` | v2.2.0 | `00a9a1b7f552d6bb4337278b10ae25aac0f4e666` | AGPL-3.0 | , with the patches below | | xk6-load-toolkit | `github.com/browserstack/xk6-load-toolkit` | the image's `org.opencontainers.image.version` label | the `commit` in `build-info.json` (also the `org.opencontainers.image.revision` label) | AGPL-3.0 | > | +### k6 patches (`k6Patches` in `extensions.json`) + +The binary links k6 with these patches applied, in this order, by `build.sh` +(`git apply` on the pinned k6 source, then `xk6 build --replace`). Both files +are in this repository, so the patched k6 source is the k6 commit above plus +these files. + +| Patch | What it changes | +|---|---| +| [`patches/k6-grpc-deadline.patch`](patches/k6-grpc-deadline.patch) | Pushes a finished gRPC call's `grpc_req_duration` sample against the VU context instead of the call's own, so calls that end with `DEADLINE_EXCEEDED` are recorded (stock k6 drops them, because the deadline cancels the call's context). | +| [`patches/k6-grpc-capture.patch`](patches/k6-grpc-capture.patch) | Adds the `lib/netext/grpccapture` package: a hook an extension can register to observe every gRPC call's stats (used by the `grpcCapture` capability) and a pacer called before each unary call and stream open (used by the throughput limiter). With nothing registered each call pays one atomic load. | + ### Third-party extensions (15, pinned in `extensions.json`) | Extension | Go module | Version | Commit | Licence | Source | @@ -93,9 +105,10 @@ All in this repository at the same commit: | File | Role | |---|---| -| [`extensions.json`](extensions.json) | The manifest: the k6 version and every extension with its pinned version. | -| [`build.sh`](build.sh) | Turns the manifest into `xk6 build --k6-version … --with @ …` and runs it with CGO off. | -| [`scripts/release-gate.sh`](scripts/release-gate.sh) | Reads the binary's `go version -m` output and fails unless every pin above is linked at exactly its version. | +| [`extensions.json`](extensions.json) | The manifest: the k6 version, the k6 patches and every extension with its pinned version. | +| [`build.sh`](build.sh) | Applies the k6 patches to a copy of the pinned k6 source at `/tmp/xk6-load-toolkit/k6--patched`, turns the manifest into `xk6 build --k6-version … --with @ … --replace go.k6.io/k6/v2=` and runs it with CGO off. | +| [`patches/`](patches) | The k6 patches listed above. | +| [`scripts/release-gate.sh`](scripts/release-gate.sh) | Reads the binary's `go version -m` output and fails unless every pin above is linked at exactly its version, and k6 is replaced by exactly the patched copy. | | This file | The builder stage below, the toolchain pins and the component list. | ### Builder stage @@ -153,6 +166,6 @@ RUN GOOS=linux GOARCH="$TARGETARCH" CGO_ENABLED=0 ./build.sh --output /out/k6 && ## Keeping this file current -A change to `extensions.json`, to the Go image or `go-version`, or to the xk6 -version must update this file in the same commit, so that this file at any +A change to `extensions.json`, to a file in `patches/`, to the Go image or +`go-version`, or to the xk6 version must update this file in the same commit, so that this file at any commit describes the binaries built from that commit. diff --git a/build.sh b/build.sh index fc1a7ee..6edb5f8 100755 --- a/build.sh +++ b/build.sh @@ -8,12 +8,18 @@ # script, --k6-version the manifest's "k6Version", --output ./dist/k6. # GOOS / GOARCH from the environment select the target; CGO is always off. # +# "k6Patches" (optional) lists repo-relative patch files applied to the k6 source +# before the build: the pinned k6 module is fetched through the Go module proxy, +# copied to a fixed directory, patched with `git apply`, and handed to xk6 with +# --replace. A patch that no longer applies (k6 version drift) fails the build, +# and so does a binary that was not linked against the patched copy. +# # Each manifest entry has exactly one of: # "repoPath": a directory relative to --repo-root -> --with = # "version": a module version -> --with @ # An entry with both, or neither, fails the build: a pin must never be ignored. # -# Requires xk6, jq and go on PATH. +# Requires xk6, jq and go on PATH (and git when k6Patches is set). set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" @@ -72,6 +78,45 @@ done < <(jq -r '.extensions[] | [.name, .module, (.repoPath // ""), (.version // [[ ${#WITH_ARGS[@]} -gt 0 ]] || { echo "[build] manifest is empty, nothing to build" >&2; exit 1; } +K6_PATCHES=() +while IFS= read -r patch_path; do + [[ -n "$patch_path" ]] && K6_PATCHES+=("$patch_path") +done < <(jq -r '(.k6Patches // [])[]' "$MANIFEST") + +REPLACE_ARGS=() +PATCHED_K6_DIR="" +if [[ ${#K6_PATCHES[@]} -gt 0 ]]; then + command -v git >/dev/null 2>&1 || { echo "[build] ERROR: git is required to apply k6Patches" >&2; exit 1; } + command -v go >/dev/null 2>&1 || { echo "[build] ERROR: go is required to apply k6Patches" >&2; exit 1; } + k6_major="${K6_VERSION#v}" + k6_major="${k6_major%%.*}" + K6_MODULE="go.k6.io/k6" + if [[ "$k6_major" =~ ^[0-9]+$ && "$k6_major" -ge 2 ]]; then + K6_MODULE="go.k6.io/k6/v${k6_major}" + fi + k6_src_dir="$(go mod download -json "${K6_MODULE}@${K6_VERSION}" | jq -r '.Dir // empty')" + [[ -n "$k6_src_dir" && -d "$k6_src_dir" ]] || { + echo "[build] ERROR: could not download ${K6_MODULE}@${K6_VERSION} source" >&2; exit 1; } + # A fixed path, not a temp dir: the replacement directory is recorded in the + # binary's build info, so a random path would make every build differ. + PATCHED_K6_DIR="/tmp/xk6-load-toolkit/k6-${K6_VERSION}-patched" + rm -rf "$PATCHED_K6_DIR" + mkdir -p "$(dirname "$PATCHED_K6_DIR")" + cp -R "$k6_src_dir" "$PATCHED_K6_DIR" + chmod -R u+w "$PATCHED_K6_DIR" + for patch_path in "${K6_PATCHES[@]}"; do + patch_file="${REPO_ROOT}/${patch_path}" + [[ -f "$patch_file" ]] || { echo "[build] ERROR: patch ${patch_path} not found at ${patch_file}" >&2; exit 1; } + if ! (cd "$PATCHED_K6_DIR" && git apply --check -p1 "$patch_file"); then + echo "[build] ERROR: patch ${patch_path} does not apply to k6 ${K6_VERSION}" >&2 + exit 1 + fi + (cd "$PATCHED_K6_DIR" && git apply -p1 "$patch_file") + echo "[build] patched k6 ${K6_VERSION} with ${patch_path}" + done + REPLACE_ARGS=(--replace "${K6_MODULE}=${PATCHED_K6_DIR}") +fi + mkdir -p "$(dirname "$OUTPUT")" echo "[build] k6=${K6_VERSION} GOOS=${GOOS:-host} GOARCH=${GOARCH:-host} output=${OUTPUT} extensions=$((${#WITH_ARGS[@]} / 2))" @@ -79,7 +124,7 @@ echo "[build] k6=${K6_VERSION} GOOS=${GOOS:-host} GOARCH=${GOARCH:-host} output= # the version only as the flag, never also as a positional argument. # Module-proxy fetches fail transiently; retry, resuming from the module cache. attempt=1 -until CGO_ENABLED=0 xk6 build --verbose --k6-version "$K6_VERSION" "${WITH_ARGS[@]}" --output "$OUTPUT"; do +until CGO_ENABLED=0 xk6 build --verbose --k6-version "$K6_VERSION" "${WITH_ARGS[@]}" ${REPLACE_ARGS[@]+"${REPLACE_ARGS[@]}"} --output "$OUTPUT"; do if [[ "$attempt" -ge 3 ]]; then echo "[build] FAILED after ${attempt} attempts" >&2 exit 1 @@ -89,4 +134,11 @@ until CGO_ENABLED=0 xk6 build --verbose --k6-version "$K6_VERSION" "${WITH_ARGS[ attempt=$((attempt + 1)) done +# A replace xk6 dropped would ship stock k6 with exit 0; the build info names the replacement. +if [[ -n "$PATCHED_K6_DIR" ]] && + ! go version -m "$OUTPUT" | awk -v dir="$PATCHED_K6_DIR" '$1 == "=>" && $2 == dir { found = 1 } END { exit !found }'; then + echo "[build] ERROR: ${OUTPUT} was not built against the patched k6 (${PATCHED_K6_DIR})" >&2 + exit 1 +fi + echo "[build] done -> $OUTPUT" diff --git a/extensions.json b/extensions.json index bf968ba..1d79215 100644 --- a/extensions.json +++ b/extensions.json @@ -1,5 +1,9 @@ { "k6Version": "v2.2.0", + "k6Patches": [ + "patches/k6-grpc-deadline.patch", + "patches/k6-grpc-capture.patch" + ], "extensions": [ { "name": "load-toolkit", diff --git a/go.mod b/go.mod index a7247f0..bb59af2 100644 --- a/go.mod +++ b/go.mod @@ -15,6 +15,7 @@ require ( github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect + github.com/golang/protobuf v1.5.4 // indirect github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 // indirect github.com/google/uuid v1.6.0 // indirect github.com/grafana/sobek v0.0.0-20260727154728-7781506a890f // indirect diff --git a/internal/config/config.go b/internal/config/config.go index 414a453..9ef2afb 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -14,6 +14,7 @@ import ( "go.k6.io/k6/v2/errext/exitcodes" + "github.com/browserstack/xk6-load-toolkit/internal/grpccapture" "github.com/browserstack/xk6-load-toolkit/internal/sink" tagfilter "github.com/browserstack/xk6-load-toolkit/internal/tag-filter" "github.com/browserstack/xk6-load-toolkit/internal/throughput" @@ -43,6 +44,8 @@ type Config struct { Throughput *throughput.Config `json:"throughput"` TagFilter *tagfilter.Config `json:"tagFilter"` Sink *sink.Config `json:"sink"` + // GRPCCapture records a sample of gRPC calls; needs the k6 gRPC hooks (see README). + GRPCCapture *grpccapture.Config `json:"grpcCapture"` } // EnvConfig lists extra variables removed from the process environment in init(). @@ -78,6 +81,14 @@ func Throughput() (*throughput.Config, error) { return loadedConfig.Throughput, nil } +// GRPCCapture returns the grpcCapture section read in init(), or the startup error. +func GRPCCapture() (*grpccapture.Config, error) { + if configErr != nil { + return nil, configErr + } + return loadedConfig.GRPCCapture, nil +} + // TagFilter returns the tagFilter section read in init(), or the startup error. func TagFilter() (*tagfilter.Config, error) { if configErr != nil { @@ -226,6 +237,11 @@ func (c *Config) Validate() error { return err } } + if c.GRPCCapture != nil { + if err := c.GRPCCapture.Validate(); err != nil { + return err + } + } if c.Sink != nil { return c.Sink.Validate() } diff --git a/internal/grpccapture/capture.go b/internal/grpccapture/capture.go new file mode 100644 index 0000000..546c822 --- /dev/null +++ b/internal/grpccapture/capture.go @@ -0,0 +1,346 @@ +package grpccapture + +import ( + "context" + "encoding/json" + "fmt" + "io" + "os" + "sort" + "strconv" + "strings" + "sync" + "syscall" + "time" + "unicode/utf8" + + protov1 "github.com/golang/protobuf/proto" //nolint:staticcheck // k6 still hands v1 messages to stats handlers + "google.golang.org/grpc/metadata" + grpcstats "google.golang.org/grpc/stats" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" +) + +const ( + // messageLimit is the per-message cap (bytes). + messageLimit = 64 * 1024 + // metadataLimit caps the serialized size of one metadata / header / trailer map. + metadataLimit = 16 * 1024 + // reflectionPrefix marks k6's own server-reflection RPC, which is never a script call. + reflectionPrefix = "/grpc.reflection." +) + +// sample is one captured call, one JSON line in the capture file. +type sample struct { + TS int64 `json:"ts"` + Scenario string `json:"scenario"` + Name string `json:"name"` + Method string `json:"method"` + Code int `json:"code"` + Request sampleRequest `json:"request"` + Response sampleResponse `json:"response"` + Truncated bool `json:"truncated"` +} + +type sampleRequest struct { + Metadata map[string]string `json:"metadata"` + Message *string `json:"message"` +} + +type sampleResponse struct { + Headers map[string]string `json:"headers"` + Trailers map[string]string `json:"trailers"` + Message *string `json:"message"` + Error *string `json:"error"` +} + +// call accumulates one RPC's stats between TagRPC and End. +type call struct { + mu sync.Mutex + fullMethod string + begin time.Time + reqMD metadata.MD + reqPayload any + respMD metadata.MD + respPayload any + trailer metadata.MD +} + +type callKey struct{} + +// recorder is the grpccapture.Handler the extension registers. +type recorder struct { + cfg config + capturing map[uint64]struct{} + open func(path string) (io.Writer, error) + now func() time.Time + + mu sync.Mutex + out io.Writer + broken bool + seenSuccess map[string]struct{} + errorsBySc map[string]map[string]struct{} + errorCount int +} + +func newRecorder(cfg config) *recorder { + return &recorder{ + cfg: cfg, + capturing: selectCapturingVUIDs(cfg.totalVUs, cfg.seed, cfg.maxCapturingVUs), + open: openCaptureFile, + now: time.Now, + seenSuccess: map[string]struct{}{}, + errorsBySc: map[string]map[string]struct{}{}, + } +} + +// openCaptureFile opens the pre-created capture file for appending. It never creates the file +// and never follows a symlink: the logs directory is world-writable and sticky, and only the +// root-created file is trusted. +func openCaptureFile(path string) (io.Writer, error) { + return os.OpenFile(path, os.O_WRONLY|os.O_APPEND|syscall.O_NOFOLLOW, 0) //nolint:gosec // fixed runner path +} + +// full reports whether both caps are reached; a full recorder ignores every later call. +func (r *recorder) full() bool { + r.mu.Lock() + defer r.mu.Unlock() + return r.broken || (len(r.seenSuccess) >= r.cfg.maxUniqueSuccess && r.errorCount >= r.cfg.maxUniqueError) +} + +// TagRPC implements the k6 grpccapture.Handler seam. +func (r *recorder) TagRPC(ctx context.Context, info *grpcstats.RPCTagInfo, vuID uint64) context.Context { + if _, ok := r.capturing[vuID]; !ok || info == nil { + return ctx + } + if strings.HasPrefix(info.FullMethodName, reflectionPrefix) || r.full() { + return ctx + } + return context.WithValue(ctx, callKey{}, &call{fullMethod: info.FullMethodName, begin: r.now()}) +} + +// HandleRPC implements the k6 grpccapture.Handler seam. +func (r *recorder) HandleRPC(ctx context.Context, stat grpcstats.RPCStats, c grpcCall) { + rec, ok := ctx.Value(callKey{}).(*call) + if !ok || rec == nil { + return + } + rec.mu.Lock() + switch s := stat.(type) { + case *grpcstats.OutHeader: + rec.reqMD = s.Header.Copy() + if s.FullMethod != "" { + rec.fullMethod = s.FullMethod + } + case *grpcstats.OutPayload: + // Keep the message, not its JSON: protojson runs in finish, only for a call that wins a + // slot, so duplicates and calls past the caps cost no conversion on the load generator. + if rec.reqPayload == nil { + rec.reqPayload = s.Payload + } + case *grpcstats.InHeader: + rec.respMD = s.Header.Copy() + case *grpcstats.InPayload: + if rec.respPayload == nil { + rec.respPayload = s.Payload + } + case *grpcstats.InTrailer: + rec.trailer = s.Trailer.Copy() + case *grpcstats.End: + if !s.BeginTime.IsZero() { + rec.begin = s.BeginTime + } + rec.mu.Unlock() + tags := map[string]string{} + if c.tags != nil { + tags = c.tags() + } + r.finish(rec, s.Error, tags) + return + } + rec.mu.Unlock() +} + +// grpcCall is the slice of k6's grpccapture.Call the recorder reads, so the logic is testable +// without the patched k6. +type grpcCall struct { + tags func() map[string]string +} + +// marshal renders a request / response message as protojson, cut at messageLimit. The bool +// reports a cut. +func marshal(payload any) (*string, bool) { + msg, ok := payload.(proto.Message) + if !ok { + v1, ok1 := payload.(protov1.Message) + if !ok1 { + return nil, false + } + msg = protov1.MessageV2(v1) + } + b, err := protojson.Marshal(msg) + if err != nil { + return nil, false + } + text, cut := truncateUTF8(string(b), messageLimit) + return &text, cut +} + +// finish decides whether the ended call is kept and appends it. +func (r *recorder) finish(rec *call, callErr error, tags map[string]string) { + st := status.Convert(callErr) + code := int(st.Code()) + scenario := tags["scenario"] + if scenario == "" { + scenario = "default" + } + name := rowName(tags, rec.fullMethod) + if code == 0 && r.excluded(name, rec.fullMethod) { + return + } + key := scenario + "|" + name + "|" + strconv.Itoa(code) + if !r.reserve(code, scenario, key) { + return + } + + rec.mu.Lock() + reqMsg, reqCut := marshal(rec.reqPayload) + s := sample{ + TS: rec.begin.UnixMilli(), + Scenario: scenario, + Name: name, + Method: rec.fullMethod, + Code: code, + Request: sampleRequest{Metadata: flattenMD(rec.reqMD), Message: reqMsg}, + Response: sampleResponse{Headers: flattenMD(rec.respMD), Trailers: flattenMD(rec.trailer)}, + Truncated: reqCut, + } + if code == 0 { + respMsg, respCut := marshal(rec.respPayload) + s.Response.Message = respMsg + s.Truncated = s.Truncated || respCut + } else { + text, cut := truncateUTF8(st.Message(), messageLimit) + s.Response.Error = &text + s.Truncated = s.Truncated || cut + } + rec.mu.Unlock() + r.write(s) +} + +// excluded reports whether an OK call is named by a GRPC exclusion rule. +func (r *recorder) excluded(name, fullMethod string) bool { + for _, rule := range r.cfg.exclude { + if rule.matches(name) || rule.matches(fullMethod) { + return true + } + } + return false +} + +// reserve claims a slot for the call under the caps; false when it is a duplicate or a cap is +// reached. OK (0) is the only success, as for every gRPC read. +func (r *recorder) reserve(code int, scenario, key string) bool { + r.mu.Lock() + defer r.mu.Unlock() + if r.broken { + return false + } + if code == 0 { + if _, seen := r.seenSuccess[key]; seen || len(r.seenSuccess) >= r.cfg.maxUniqueSuccess { + return false + } + r.seenSuccess[key] = struct{}{} + return true + } + set := r.errorsBySc[scenario] + if set == nil { + set = map[string]struct{}{} + r.errorsBySc[scenario] = set + } + if _, seen := set[key]; seen || len(set) >= r.cfg.maxErrorsPerScenario || r.errorCount >= r.cfg.maxUniqueError { + return false + } + set[key] = struct{}{} + r.errorCount++ + return true +} + +// write appends one JSON line. A failure to open or write turns capture off for the run. +func (r *recorder) write(s sample) { + line, err := json.Marshal(s) + if err != nil { + return + } + line = append(line, '\n') + r.mu.Lock() + defer r.mu.Unlock() + if r.broken { + return + } + if r.out == nil { + out, openErr := r.open(r.cfg.path) + if openErr != nil { + r.broken = true + // No path, no data: the reason only (k6's stderr reaches the customer log). + fmt.Fprintf(os.Stderr, "[grpc-capture] capture file unavailable; gRPC capture off for this run\n") + return + } + r.out = out + } + if _, err := r.out.Write(line); err != nil { + r.broken = true + fmt.Fprintf(os.Stderr, "[grpc-capture] capture write failed; gRPC capture off for this run\n") + } +} + +// rowName is the call's row label, as the sink names the gRPC call row: the `name` tag, else /package.Service/Method. +func rowName(tags map[string]string, fullMethod string) string { + if name := tags["name"]; name != "" { + return name + } + if service, method := tags["service"], tags["method"]; service != "" && method != "" { + return "/" + service + "/" + method + } + if url := tags["url"]; url != "" { + if i := strings.Index(url, "/"); i >= 0 { + return url[i:] + } + return url + } + return fullMethod +} + +// flattenMD renders metadata as name -> comma-joined values, capped at metadataLimit in total. +// Keys are walked in sorted order so the same metadata always keeps the same entries at the cap. +func flattenMD(md metadata.MD) map[string]string { + out := make(map[string]string, len(md)) + keys := make([]string, 0, len(md)) + for k := range md { + keys = append(keys, k) + } + sort.Strings(keys) + size := 0 + for _, k := range keys { + v := strings.Join(md[k], ", ") + size += len(k) + len(v) + if size > metadataLimit { + break + } + out[k] = v + } + return out +} + +// truncateUTF8 cuts s to at most limit bytes without splitting a rune. +func truncateUTF8(s string, limit int) (string, bool) { + if len(s) <= limit { + return s, false + } + cut := limit + for cut > 0 && !utf8.RuneStart(s[cut]) { + cut-- + } + return s[:cut], true +} diff --git a/internal/grpccapture/capture_test.go b/internal/grpccapture/capture_test.go new file mode 100644 index 0000000..721bfda --- /dev/null +++ b/internal/grpccapture/capture_test.go @@ -0,0 +1,413 @@ +package grpccapture + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "testing" + "time" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" + grpcstats "google.golang.org/grpc/stats" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/structpb" +) + +// Run with `go test -tags stock_k6 ./...` against stock k6, or plain `go test` against the +// patched k6 that build.sh produces. + +func baseEnv() *Config { + return &Config{File: "/tmp/unused", TotalVUs: 1, MaxSuccess: 20, MaxErrors: 30} +} + +type memSink struct{ bytes.Buffer } + +func newTestRecorder(t *testing.T, env *Config) (*recorder, *memSink) { + t.Helper() + if err := env.Validate(); err != nil { + t.Fatalf("invalid test config: %v", err) + } + r := newRecorder(resolve(env)) + sink := &memSink{} + r.open = func(string) (io.Writer, error) { return sink, nil } + r.now = func() time.Time { return time.UnixMilli(1762761712010) } + return r, sink +} + +func (m *memSink) samples(t *testing.T) []sample { + t.Helper() + var out []sample + for _, line := range strings.Split(strings.TrimSpace(m.String()), "\n") { + if line == "" { + continue + } + var s sample + if err := json.Unmarshal([]byte(line), &s); err != nil { + t.Fatalf("bad line %q: %v", line, err) + } + out = append(out, s) + } + return out +} + +// runCall drives one RPC through the recorder the way k6's stats handler does. +func runCall(t *testing.T, r *recorder, vu uint64, method string, tags map[string]string, callErr error) { + t.Helper() + ctx := r.TagRPC(context.Background(), &grpcstats.RPCTagInfo{FullMethodName: method}, vu) + c := grpcCall{tags: func() map[string]string { return tags }} + req, _ := structpb.NewStruct(map[string]any{"orderId": "A-1001"}) + resp, _ := structpb.NewStruct(map[string]any{"ok": true}) + r.HandleRPC(ctx, &grpcstats.OutHeader{FullMethod: method, Header: metadata.Pairs("authorization", "Bearer x", "tenant", "acme")}, c) + r.HandleRPC(ctx, &grpcstats.OutPayload{Payload: req}, c) + r.HandleRPC(ctx, &grpcstats.InHeader{Header: metadata.Pairs("content-type", "application/grpc")}, c) + if callErr == nil { + r.HandleRPC(ctx, &grpcstats.InPayload{Payload: resp}, c) + } + r.HandleRPC(ctx, &grpcstats.InTrailer{Trailer: metadata.Pairs("grpc-status", "0")}, c) + r.HandleRPC(ctx, &grpcstats.End{BeginTime: time.UnixMilli(1762761700000), Error: callErr}, c) +} + +func TestSelectCapturingVUIDsIsTheReferenceShuffle(t *testing.T) { + // Expected sets computed by a JavaScript implementation of the same seeded shuffle. + cases := []struct { + n int + seed uint32 + want []uint64 + }{ + {5, 0, []uint64{1, 2, 3, 4, 5}}, + {50, 12345, []uint64{1, 5, 8, 10, 12, 16, 17, 22, 24, 27, 30, 33, 34, 36, 41, 42, 43, 46, 47, 50}}, + {1000, 32767, []uint64{16, 18, 34, 36, 54, 92, 118, 162, 180, 208, 230, 238, 254, 286, 459, 486, 545, 576, 699, 729}}, + {30, 4294967295, []uint64{1, 2, 3, 6, 7, 8, 10, 11, 12, 14, 16, 17, 19, 20, 21, 22, 24, 25, 27, 29}}, + } + for _, tc := range cases { + got := make([]uint64, 0, defaultMaxCapturingVUs) + for id := range selectCapturingVUIDs(tc.n, tc.seed, defaultMaxCapturingVUs) { + got = append(got, id) + } + sort.Slice(got, func(i, j int) bool { return got[i] < got[j] }) + if strings.Join(strings.Fields(strings.Trim(jsonOf(got), "[]")), "") != strings.Trim(jsonOf(tc.want), "[]") { + t.Errorf("n=%d seed=%d: got %v want %v", tc.n, tc.seed, got, tc.want) + } + } +} + +func jsonOf(v any) string { + b, _ := json.Marshal(v) + return string(b) +} + +func TestConfigValidateAndResolve(t *testing.T) { + c := &Config{ + File: "/x", TotalVUs: 40, VUSeed: -1, MaxSuccess: 10, MaxErrors: 15, + Exclude: []ExcludeRule{{Pattern: "/a.B/C"}, {Pattern: "^/pay\\.", Regex: true}}, + } + if err := c.Validate(); err != nil { + t.Fatal(err) + } + cfg := resolve(c) + if cfg.totalVUs != 40 || cfg.seed != 4294967295 || cfg.maxUniqueSuccess != 10 || cfg.maxUniqueError != 15 { + t.Fatalf("unexpected cfg %+v", cfg) + } + if cfg.maxCapturingVUs != defaultMaxCapturingVUs || cfg.maxErrorsPerScenario != defaultMaxErrorsPerScenario { + t.Fatalf("defaults %+v", cfg) + } + if len(cfg.exclude) != 2 || cfg.exclude[0].pattern != "/a.B/C" || cfg.exclude[1].regex == nil { + t.Fatalf("exclude %+v", cfg.exclude) + } + if resolve(&Config{File: "/x"}).totalVUs != 1 { + t.Fatal("totalVUs must default to 1") + } + + for name, bad := range map[string]*Config{ + "no file": {}, + "negative cap": {File: "/x", MaxErrors: -1}, + "empty pattern": {File: "/x", Exclude: []ExcludeRule{{}}}, + "bad regex": {File: "/x", Exclude: []ExcludeRule{{Pattern: "(", Regex: true}}}, + } { + if bad.Validate() == nil { + t.Errorf("%s: want a validation error", name) + } + } +} + +func TestCapturesAnOKAndAnErrorCall(t *testing.T) { + r, sink := newTestRecorder(t, baseEnv()) + tags := map[string]string{"scenario": "orders", "name": "place-order"} + runCall(t, r, 1, "/orders.OrderService/PlaceOrder", tags, nil) + runCall(t, r, 1, "/orders.OrderService/PlaceOrder", tags, status.Error(codes.Unavailable, "connection refused")) + + got := sink.samples(t) + if len(got) != 2 { + t.Fatalf("want 2 samples, got %d", len(got)) + } + ok, failed := got[0], got[1] + if ok.Code != 0 || ok.Name != "place-order" || ok.Scenario != "orders" || ok.Method != "/orders.OrderService/PlaceOrder" { + t.Fatalf("ok sample %+v", ok) + } + if ok.TS != 1762761700000 { + t.Fatalf("ts %d", ok.TS) + } + if ok.Request.Message == nil || *ok.Request.Message != `{"orderId":"A-1001"}` { + t.Fatalf("request message %v", ok.Request.Message) + } + if ok.Response.Message == nil || *ok.Response.Message != `{"ok":true}` || ok.Response.Error != nil { + t.Fatalf("response %+v", ok.Response) + } + // Metadata is written as received; k6ReqToClickhouse.js redacts it before publishing. + if ok.Request.Metadata["tenant"] != "acme" || ok.Response.Headers["content-type"] != "application/grpc" || + ok.Response.Trailers["grpc-status"] != "0" { + t.Fatalf("metadata %+v / %+v", ok.Request, ok.Response) + } + if failed.Code != 14 || failed.Response.Message != nil || failed.Response.Error == nil || + *failed.Response.Error != "connection refused" { + t.Fatalf("error sample %+v", failed) + } +} + +func TestSkipsNonCapturingVUsAndReflection(t *testing.T) { + env := baseEnv() + env.TotalVUs = 50 + env.VUSeed = 12345 + r, sink := newTestRecorder(t, env) + // VU 2 is not in the seed-12345 selection; VU 1 is. + runCall(t, r, 2, "/a.B/C", map[string]string{}, nil) + runCall(t, r, 1, "/grpc.reflection.v1.ServerReflection/ServerReflectionInfo", map[string]string{}, nil) + if sink.Len() != 0 { + t.Fatalf("captured %q", sink.String()) + } + runCall(t, r, 1, "/a.B/C", map[string]string{}, nil) + if got := sink.samples(t); len(got) != 1 || got[0].Name != "/a.B/C" || got[0].Scenario != "default" { + t.Fatalf("got %+v", got) + } +} + +func TestDedupesAndCaps(t *testing.T) { + env := baseEnv() + env.MaxSuccess, env.MaxErrors = 2, 3 + r, sink := newTestRecorder(t, env) + for i := 0; i < 3; i++ { + runCall(t, r, 1, "/a.B/One", map[string]string{}, nil) // one OK combination, deduped + } + runCall(t, r, 1, "/a.B/Two", map[string]string{}, nil) + runCall(t, r, 1, "/a.B/Three", map[string]string{}, nil) // over the success cap + for _, code := range []codes.Code{codes.Internal, codes.NotFound, codes.Aborted, codes.DataLoss} { + runCall(t, r, 1, "/a.B/One", map[string]string{}, status.Error(code, "x")) // 4th error is over the cap + } + var ok, failed int + for _, s := range sink.samples(t) { + if s.Code == 0 { + ok++ + } else { + failed++ + } + } + if ok != 2 || failed != 3 { + t.Fatalf("ok=%d failed=%d", ok, failed) + } + if !r.full() { + t.Fatal("both caps reached but recorder not full") + } + // A full recorder attaches no per-call state at all. + if ctx := r.TagRPC(context.Background(), &grpcstats.RPCTagInfo{FullMethodName: "/a.B/C"}, 1); ctx.Value(callKey{}) != nil { + t.Fatal("full recorder still tracks calls") + } +} + +func TestPerScenarioErrorCap(t *testing.T) { + env := baseEnv() + env.MaxSuccess, env.MaxErrors = 100, 150 + r, sink := newTestRecorder(t, env) + for i := 0; i < 20; i++ { + runCall(t, r, 1, "/a.B/M"+strings.Repeat("x", i), map[string]string{"scenario": "s1"}, status.Error(codes.Internal, "x")) + } + runCall(t, r, 1, "/a.B/M", map[string]string{"scenario": "s2"}, status.Error(codes.Internal, "x")) + counts := map[string]int{} + for _, s := range sink.samples(t) { + counts[s.Scenario]++ + } + if counts["s1"] != defaultMaxErrorsPerScenario || counts["s2"] != 1 { + t.Fatalf("counts %+v", counts) + } +} + +func TestExclusionDropsOnlyOKCalls(t *testing.T) { + env := baseEnv() + env.Exclude = []ExcludeRule{{Pattern: "/a.B/Health"}} + r, sink := newTestRecorder(t, env) + runCall(t, r, 1, "/a.B/Health", map[string]string{}, nil) + runCall(t, r, 1, "/a.B/Health", map[string]string{}, status.Error(codes.Unavailable, "down")) + got := sink.samples(t) + if len(got) != 1 || got[0].Code != 14 { + t.Fatalf("got %+v", got) + } +} + +// TC-026: k6 names a call "/pkg.Service/Method"; customers (and the JMeter path) write the +// rule without the leading slash. Either spelling must match either side. +func TestExcludeRuleMatchesWithOrWithoutLeadingSlash(t *testing.T) { + exact := func(p string) excludeRule { return excludeRule{pattern: p} } + re := func(p string) excludeRule { return excludeRule{pattern: p, regex: regexp.MustCompile(p)} } + cases := []struct { + desc string + rule excludeRule + name string + want bool + }{ + {"exact, rule without slash", exact("quickpizza.GRPC/RatePizza"), "/quickpizza.GRPC/RatePizza", true}, + {"exact, rule with slash", exact("/quickpizza.GRPC/RatePizza"), "/quickpizza.GRPC/RatePizza", true}, + {"exact, rule with slash, name without", exact("/quickpizza.GRPC/RatePizza"), "quickpizza.GRPC/RatePizza", true}, + {"exact, different method", exact("quickpizza.GRPC/RatePizza"), "/quickpizza.GRPC/GetPizza", false}, + {"exact, only one slash trimmed", exact("quickpizza.GRPC/RatePizza"), "//quickpizza.GRPC/RatePizza", false}, + {"exact, empty name", exact("quickpizza.GRPC/RatePizza"), "", false}, + {"regex anchored without slash", re(`^quickpizza\.GRPC/Rate.*$`), "/quickpizza.GRPC/RatePizza", true}, + {"regex anchored with slash", re(`^/quickpizza\.GRPC/Rate.*$`), "/quickpizza.GRPC/RatePizza", true}, + {"regex, non-matching name", re(`^quickpizza\.GRPC/Rate.*$`), "/quickpizza.GRPC/GetPizza", false}, + {"regex, empty name", re(`.*`), "", false}, + } + for _, tc := range cases { + if got := tc.rule.matches(tc.name); got != tc.want { + t.Errorf("%s: matches(%q) with pattern %q = %v, want %v", tc.desc, tc.name, tc.rule.pattern, got, tc.want) + } + } +} + +func TestExclusionWithoutLeadingSlashDropsTheOKCall(t *testing.T) { + env := baseEnv() + env.Exclude = []ExcludeRule{{Pattern: "quickpizza.GRPC/RatePizza"}} + r, sink := newTestRecorder(t, env) + runCall(t, r, 1, "/quickpizza.GRPC/RatePizza", map[string]string{}, nil) + runCall(t, r, 1, "/quickpizza.GRPC/GetPizza", map[string]string{}, nil) + got := sink.samples(t) + if len(got) != 1 || got[0].Method != "/quickpizza.GRPC/GetPizza" { + t.Fatalf("got %+v", got) + } +} + +func TestMessagesAreCutAt64KB(t *testing.T) { + r, sink := newTestRecorder(t, baseEnv()) + ctx := r.TagRPC(context.Background(), &grpcstats.RPCTagInfo{FullMethodName: "/a.B/C"}, 1) + big, _ := structpb.NewStruct(map[string]any{"blob": strings.Repeat("é", messageLimit)}) + c := grpcCall{} + r.HandleRPC(ctx, &grpcstats.OutPayload{Payload: big}, c) + r.HandleRPC(ctx, &grpcstats.End{Error: status.Error(codes.Internal, strings.Repeat("e", messageLimit+10))}, c) + s := sink.samples(t)[0] + if !s.Truncated || len(*s.Request.Message) > messageLimit || len(*s.Response.Error) != messageLimit { + t.Fatalf("not truncated: %d / %d", len(*s.Request.Message), len(*s.Response.Error)) + } + if !strings.HasPrefix(*s.Request.Message, `{"blob":"é`) { + t.Fatalf("prefix %q", (*s.Request.Message)[:20]) + } +} + +func TestUntrackedContextAndUnknownPayloadsAreIgnored(t *testing.T) { + r, sink := newTestRecorder(t, baseEnv()) + r.HandleRPC(context.Background(), &grpcstats.End{}, grpcCall{}) + ctx := r.TagRPC(context.Background(), &grpcstats.RPCTagInfo{FullMethodName: "/a.B/C"}, 1) + r.HandleRPC(ctx, &grpcstats.OutPayload{Payload: "not a proto"}, grpcCall{}) + r.HandleRPC(ctx, &grpcstats.End{}, grpcCall{}) + got := sink.samples(t) + if len(got) != 1 || got[0].Request.Message != nil { + t.Fatalf("got %+v", got) + } +} + +func TestOpenFailureTurnsCaptureOff(t *testing.T) { + r, _ := newTestRecorder(t, baseEnv()) + r.open = func(string) (io.Writer, error) { return nil, errors.New("nope") } + runCall(t, r, 1, "/a.B/C", map[string]string{}, nil) + if !r.full() { + t.Fatal("broken recorder still accepts calls") + } +} + +func TestOpenCaptureFileNeverCreatesOrFollowsLinks(t *testing.T) { + dir := t.TempDir() + if _, err := openCaptureFile(filepath.Join(dir, "missing.jsonl")); err == nil { + t.Fatal("created a capture file that the entrypoint did not pre-create") + } + target := filepath.Join(dir, "target") + if err := os.WriteFile(target, nil, 0o600); err != nil { + t.Fatal(err) + } + link := filepath.Join(dir, "link.jsonl") + if err := os.Symlink(target, link); err != nil { + t.Fatal(err) + } + if _, err := openCaptureFile(link); err == nil { + t.Fatal("followed a symlink") + } + w, err := openCaptureFile(target) + if err != nil { + t.Fatal(err) + } + if _, err := w.Write([]byte("x\n")); err != nil { + t.Fatal(err) + } + _ = w.(io.Closer).Close() + if b, _ := os.ReadFile(target); string(b) != "x\n" { + t.Fatalf("content %q", b) + } +} + +func TestRowName(t *testing.T) { + cases := []struct { + tags map[string]string + want string + }{ + {map[string]string{"name": "tagged"}, "tagged"}, + {map[string]string{"service": "a.B", "method": "C"}, "/a.B/C"}, + {map[string]string{"url": "host:443/a.B/C"}, "/a.B/C"}, + {map[string]string{"url": "host"}, "host"}, + {map[string]string{}, "/full/Method"}, + } + for _, tc := range cases { + if got := rowName(tc.tags, "/full/Method"); got != tc.want { + t.Errorf("rowName(%v) = %q, want %q", tc.tags, got, tc.want) + } + } +} + +func TestFlattenMDCapsTotalSize(t *testing.T) { + md := metadata.MD{} + for i := 0; i < 40; i++ { + md.Set("k"+strings.Repeat("x", i), strings.Repeat("v", 1024)) + } + out := flattenMD(md) + total := 0 + for k, v := range out { + total += len(k) + len(v) + } + if total > metadataLimit || len(out) == 0 || len(out) == 40 { + t.Fatalf("total %d entries %d", total, len(out)) + } +} + +func TestFlattenMDKeepsTheSameEntriesEveryTime(t *testing.T) { + md := metadata.MD{} + for i := 0; i < 40; i++ { + md.Set("k"+strings.Repeat("x", i), strings.Repeat("v", 1024)) + } + first := flattenMD(md) + for i := 0; i < 20; i++ { + got := flattenMD(md) + if len(got) != len(first) { + t.Fatalf("run %d kept %d entries, first run kept %d", i, len(got), len(first)) + } + for k := range first { + if _, ok := got[k]; !ok { + t.Fatalf("run %d dropped %q", i, k) + } + } + } + if _, ok := first["k"]; !ok { + t.Fatalf("the smallest key in sort order must be kept: %v", first) + } +} diff --git a/internal/grpccapture/config.go b/internal/grpccapture/config.go new file mode 100644 index 0000000..1b2daa8 --- /dev/null +++ b/internal/grpccapture/config.go @@ -0,0 +1,164 @@ +// Package grpccapture is the gRPC capture capability: it records a bounded sample of a run's +// gRPC calls (request message and metadata, response message or error, headers and trailers) +// as JSON lines in a file the caller provides. +// +// It observes calls through the go.k6.io/k6/v2/lib/netext/grpccapture hook that +// patches/k6-grpc-capture.patch adds to k6's gRPC stats handler, so the recording part +// builds only against the patched k6 that build.sh produces (see hook.go). Built with +// -tags stock_k6 the capability compiles to a no-op, which is how the unit tests run. +// +// What it keeps: calls from at most maxCapturingVUs VUs, chosen by a seeded shuffle of the +// run's VU ids; at most one sample per (scenario, call name, status code); at most +// MaxSuccess distinct successful calls and MaxErrors failing ones, and at most +// MaxErrorsPerScenario failing ones per scenario; no OK call an exclude rule names. +// Messages are protojson, cut at 64 KB; each metadata map is cut at 16 KB. +// +// The file is opened for appending without O_CREATE and with O_NOFOLLOW, so the capability +// never creates a file or follows a link; the caller pre-creates it. Nothing is written to +// stdout. Metadata is written as received: redact it before it leaves the machine. +package grpccapture + +import ( + "errors" + "fmt" + "regexp" + "strings" +) + +const ( + defaultMaxCapturingVUs = 20 + defaultMaxErrorsPerScenario = 13 +) + +// Config is the grpcCapture section. Present means capture is on. +type Config struct { + // File is the pre-created file samples are appended to. Required. + File string `json:"file"` + // TotalVUs is the number of VU ids (1..TotalVUs) capturing VUs are chosen from. + TotalVUs int `json:"totalVUs"` + // VUSeed seeds the shuffle that picks the capturing VUs; it is truncated to 32 bits, as + // JavaScript's `seed >>> 0` does, so a JS capturer with the same seed picks the same VUs. + VUSeed int64 `json:"vuSeed"` + // MaxCapturingVUs caps how many VUs capture (default 20). + MaxCapturingVUs int `json:"maxCapturingVUs"` + // MaxSuccess and MaxErrors cap the distinct successful and failing calls kept. + MaxSuccess int `json:"maxSuccess"` + MaxErrors int `json:"maxErrors"` + // MaxErrorsPerScenario caps the failing calls kept per scenario (default 13). + MaxErrorsPerScenario int `json:"maxErrorsPerScenario"` + // Exclude lists OK calls that are never kept. + Exclude []ExcludeRule `json:"exclude"` +} + +// ExcludeRule names calls by their row name or full method. A path rule compares with one +// leading "/" trimmed from both sides; a regex rule is tried with and without it. +type ExcludeRule struct { + Pattern string `json:"pattern"` + Regex bool `json:"regex"` +} + +// Validate checks the section. +func (c *Config) Validate() error { + if strings.TrimSpace(c.File) == "" { + return errors.New("grpcCapture.file: required") + } + for name, v := range map[string]int{ + "totalVUs": c.TotalVUs, "maxCapturingVUs": c.MaxCapturingVUs, "maxSuccess": c.MaxSuccess, + "maxErrors": c.MaxErrors, "maxErrorsPerScenario": c.MaxErrorsPerScenario, + } { + if v < 0 { + return fmt.Errorf("grpcCapture.%s: must not be negative (got %d)", name, v) + } + } + for i, r := range c.Exclude { + if r.Pattern == "" { + return fmt.Errorf("grpcCapture.exclude[%d].pattern: required", i) + } + if r.Regex { + if _, err := regexp.Compile(r.Pattern); err != nil { + return fmt.Errorf("grpcCapture.exclude[%d].pattern: invalid regex: %w", i, err) + } + } + } + return nil +} + +// excludeRule is a compiled ExcludeRule. +type excludeRule struct { + pattern string + regex *regexp.Regexp +} + +// matches reports whether the rule names a call. k6's call name and full method start with +// "/" (/pkg.Service/Method) while a rule is usually written without it. +func (r excludeRule) matches(name string) bool { + if name == "" { + return false + } + bare := strings.TrimPrefix(name, "/") + if r.regex != nil { + return r.regex.MatchString(name) || r.regex.MatchString(bare) + } + return bare == strings.TrimPrefix(r.pattern, "/") +} + +// config is the resolved capture configuration. +type config struct { + path string + totalVUs int + seed uint32 + maxCapturingVUs int + maxUniqueSuccess int + maxUniqueError int + maxErrorsPerScenario int + exclude []excludeRule +} + +// resolve fills the defaults. Call it on a validated Config. +func resolve(c *Config) config { + cfg := config{ + path: c.File, + totalVUs: max(c.TotalVUs, 1), + seed: uint32(c.VUSeed), //nolint:gosec // documented 32-bit truncation + maxCapturingVUs: c.MaxCapturingVUs, + maxUniqueSuccess: c.MaxSuccess, + maxUniqueError: c.MaxErrors, + maxErrorsPerScenario: c.MaxErrorsPerScenario, + } + if cfg.maxCapturingVUs == 0 { + cfg.maxCapturingVUs = defaultMaxCapturingVUs + } + if cfg.maxErrorsPerScenario == 0 { + cfg.maxErrorsPerScenario = defaultMaxErrorsPerScenario + } + for _, r := range c.Exclude { + rule := excludeRule{pattern: r.Pattern} + if r.Regex { + rule.regex = regexp.MustCompile(r.Pattern) // validated + } + cfg.exclude = append(cfg.exclude, rule) + } + return cfg +} + +// selectCapturingVUIDs picks the capturing VUs: a seeded Fisher-Yates shuffle of 1..n with a +// 32-bit LCG (s = 1664525*s + 1013904223), keeping the first min(n, limit) ids. The same seed +// and n always pick the same VUs, so another capturer using this shuffle samples them too. +func selectCapturingVUIDs(n int, seed uint32, limit int) map[uint64]struct{} { + ids := make([]uint64, n) + for i := range ids { + ids[i] = uint64(i + 1) + } + s := seed + for i := n - 1; i > 0; i-- { + s = 1664525*s + 1013904223 + j := int(s % uint32(i+1)) //nolint:gosec // i+1 <= n, which came from a positive int + ids[i], ids[j] = ids[j], ids[i] + } + count := min(n, limit) + out := make(map[uint64]struct{}, count) + for _, id := range ids[:count] { + out[id] = struct{}{} + } + return out +} diff --git a/internal/grpccapture/hook.go b/internal/grpccapture/hook.go new file mode 100644 index 0000000..f585ab0 --- /dev/null +++ b/internal/grpccapture/hook.go @@ -0,0 +1,33 @@ +//go:build !stock_k6 + +package grpccapture + +import ( + "context" + + k6capture "go.k6.io/k6/v2/lib/netext/grpccapture" + grpcstats "google.golang.org/grpc/stats" +) + +// HooksAvailable reports whether this binary carries the k6 gRPC hooks. +const HooksAvailable = true + +// handler adapts the recorder to the hook patches/k6-grpc-capture.patch adds to k6. +type handler struct{ r *recorder } + +func (h handler) TagRPC(ctx context.Context, info *grpcstats.RPCTagInfo, vuID uint64) context.Context { + return h.r.TagRPC(ctx, info, vuID) +} + +func (h handler) HandleRPC(ctx context.Context, stat grpcstats.RPCStats, c k6capture.Call) { + h.r.HandleRPC(ctx, stat, grpcCall{tags: c.Tags}) +} + +// Register installs the recorder with k6 when the section is present. With no section nothing +// is registered and k6's stats handler pays one atomic load per stat. +func Register(cfg *Config) { + if cfg == nil { + return + } + k6capture.Register(handler{r: newRecorder(resolve(cfg))}) +} diff --git a/internal/grpccapture/hook_stock.go b/internal/grpccapture/hook_stock.go new file mode 100644 index 0000000..be5974c --- /dev/null +++ b/internal/grpccapture/hook_stock.go @@ -0,0 +1,10 @@ +//go:build stock_k6 + +package grpccapture + +// HooksAvailable reports whether this binary carries the k6 gRPC hooks. A stock_k6 build +// (the unit tests) has none. +const HooksAvailable = false + +// Register is a no-op without the k6 gRPC hooks. +func Register(*Config) {} diff --git a/internal/throughput/grpc.go b/internal/throughput/grpc.go new file mode 100644 index 0000000..7e7a143 --- /dev/null +++ b/internal/throughput/grpc.go @@ -0,0 +1,25 @@ +package throughput + +import "context" + +// GRPCPacer is what k6's gRPC client interceptors call before each unary call and each stream +// open (the hook patches/k6-grpc-capture.patch adds): one grant from the limiter the JS module +// uses, so HTTP and gRPC share one target. Messages inside a stream take nothing. +// +// The wait runs on the call's own context, so it ends early, without a grant, when the run +// stops or the call's deadline passes; k6 then fails the call before anything is sent and +// records it as a failed call, so a deadline that expires in the queue still counts. A call's +// timeout is already running while it waits, which only matters when the backlog per process +// exceeds the timeout. +// +// No limiter (section absent) or a misconfigured one is a no-op here: the JS module's +// _enabled() throws on a bad configuration, which fails the run before any gRPC call is made. +func (r *RootModule) GRPCPacer() func(context.Context) error { + return func(ctx context.Context) error { + l, err := r.shared() + if err != nil || l == nil { + return nil + } + return l.Acquire(ctx) + } +} diff --git a/internal/throughput/grpc_hook.go b/internal/throughput/grpc_hook.go new file mode 100644 index 0000000..2df0355 --- /dev/null +++ b/internal/throughput/grpc_hook.go @@ -0,0 +1,9 @@ +//go:build !stock_k6 + +package throughput + +import k6capture "go.k6.io/k6/v2/lib/netext/grpccapture" + +// RegisterGRPCPacer installs the pacer in k6's gRPC client interceptors (the hook +// patches/k6-grpc-capture.patch adds), so gRPC calls share the limiter. +func (r *RootModule) RegisterGRPCPacer() { k6capture.RegisterPacer(r.GRPCPacer()) } diff --git a/internal/throughput/grpc_hook_stock.go b/internal/throughput/grpc_hook_stock.go new file mode 100644 index 0000000..f294e52 --- /dev/null +++ b/internal/throughput/grpc_hook_stock.go @@ -0,0 +1,6 @@ +//go:build stock_k6 + +package throughput + +// RegisterGRPCPacer is a no-op without the k6 gRPC hooks. +func (r *RootModule) RegisterGRPCPacer() {} diff --git a/internal/throughput/grpc_test.go b/internal/throughput/grpc_test.go new file mode 100644 index 0000000..be9fd56 --- /dev/null +++ b/internal/throughput/grpc_test.go @@ -0,0 +1,96 @@ +package throughput + +import ( + "context" + "errors" + "testing" + "time" +) + +func rootWith(cfg *Config, err error) *RootModule { + return NewModule(func() (*Config, error) { return cfg, err }) +} + +// A gRPC call takes one grant from the same limiter the JS module instances use, so HTTP and +// gRPC share one target. +func TestGRPCPacerSharesTheModuleLimiter(t *testing.T) { + r := rootWith(&Config{PodRPS: 50}, nil) + l, err := r.shared() + if err != nil || l == nil { + t.Fatalf("shared() = %v, %v; want a limiter", l, err) + } + l.EnableTrace() + + pace := r.GRPCPacer() + for i := 0; i < 3; i++ { // e.g. two unary calls and one stream open + if err := pace(context.Background()); err != nil { + t.Fatal(err) + } + } + if got := len(l.Trace()); got != 3 { + t.Fatalf("3 paced gRPC calls took %d grants, want 3", got) + } + + m, ok := r.NewModuleInstance(nil).(*moduleInstance) + if !ok || m.root.limiter != l { + t.Fatal("the JS module instance does not share the gRPC pacer's limiter") + } + if err := m.root.limiter.Acquire(context.Background()); err != nil { + t.Fatal(err) + } + if got := len(l.Trace()); got != 4 { + t.Fatalf("module grant after 3 gRPC grants: ledger has %d, want 4", got) + } +} + +func TestGRPCPacerWithoutThroughputIsANoOp(t *testing.T) { + pace := rootWith(nil, nil).GRPCPacer() + start := time.Now() + for i := 0; i < 100; i++ { + if err := pace(context.Background()); err != nil { + t.Fatal(err) + } + } + if d := time.Since(start); d > 50*time.Millisecond { + t.Fatalf("100 unpaced calls took %v; nothing should wait without a rate", d) + } +} + +// A bad configuration fails the run through the JS module's _enabled(); the pacer must not +// turn it into a per-call gRPC error as well. +func TestGRPCPacerIgnoresAMisconfiguredSection(t *testing.T) { + r := rootWith(nil, errors.New("bad section")) + if _, err := r.shared(); err == nil { + t.Fatal("shared() hid the load error") + } + if err := r.GRPCPacer()(context.Background()); err != nil { + t.Fatalf("pacer returned %v for a misconfigured section, want nil", err) + } +} + +// A call whose context ends while it waits (run stopping, or its deadline) must not hang and +// must not consume a grant. +func TestGRPCPacerStopsWaitingWhenTheCallEnds(t *testing.T) { + r := rootWith(&Config{PodRPS: 1}, nil) + l, _ := r.shared() + l.EnableTrace() + pace := r.GRPCPacer() + if err := pace(context.Background()); err != nil { // fills the window + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + done := make(chan error, 1) + go func() { done <- pace(ctx) }() + select { + case err := <-done: + if err == nil { + t.Fatal("expected the wait to end with the context, got a grant") + } + case <-time.After(500 * time.Millisecond): + t.Fatal("pacer did not return after the call's context ended") + } + if got := len(l.Trace()); got != 1 { + t.Fatalf("ledger has %d grants after a cancelled wait, want 1", got) + } +} diff --git a/internal/throughput/module.go b/internal/throughput/module.go index 698ea37..138cb7d 100644 --- a/internal/throughput/module.go +++ b/internal/throughput/module.go @@ -52,6 +52,13 @@ func NewModule(load func() (*Config, error)) *RootModule { return &RootModule{lo // NewModuleInstance implements modules.Module. func (r *RootModule) NewModuleInstance(vu modules.VU) modules.Instance { + r.init() + return &moduleInstance{vu: vu, root: r} +} + +// init builds the process's one limiter on first use. The JS module and the gRPC pacer +// (grpc.go) share it, so HTTP requests and gRPC calls draw from one rate. +func (r *RootModule) init() { r.once.Do(func() { cfg, err := r.load() if err != nil { @@ -63,7 +70,12 @@ func (r *RootModule) NewModuleInstance(vu modules.VU) modules.Instance { r.traceTo = cfg.TraceFile } }) - return &moduleInstance{vu: vu, root: r} +} + +// shared returns the process's limiter (nil when the section is absent) or its error. +func (r *RootModule) shared() (limiter, error) { + r.init() + return r.limiter, r.err } // Schedule bounds. diff --git a/patches/k6-grpc-capture.patch b/patches/k6-grpc-capture.patch new file mode 100644 index 0000000..28fbce3 --- /dev/null +++ b/patches/k6-grpc-capture.patch @@ -0,0 +1,195 @@ +diff --git a/internal/lib/netext/grpcext/conn.go b/internal/lib/netext/grpcext/conn.go +index 7b7d904..88612b4 100644 +--- a/internal/lib/netext/grpcext/conn.go ++++ b/internal/lib/netext/grpcext/conn.go +@@ -13,6 +13,7 @@ import ( + "github.com/sirupsen/logrus" + + "go.k6.io/k6/v2/lib" ++ "go.k6.io/k6/v2/lib/netext/grpccapture" + "go.k6.io/k6/v2/metrics" + + protov1 "github.com/golang/protobuf/proto" //nolint:staticcheck,nolintlint // this is the old v1 version +@@ -91,9 +92,56 @@ func DefaultOptions(getState func() *lib.State, getVUCtx func() context.Context) + grpc.WithReturnConnectionError(), //nolint:staticcheck + grpc.WithStatsHandler(statsHandler{getState: getState, getVUCtx: getVUCtx}), + grpc.WithContextDialer(dialer), ++ // xk6-load-toolkit: pace each unary call and each stream open with a registered pacer. ++ grpc.WithChainUnaryInterceptor(paceUnary(statsHandler{getState: getState, getVUCtx: getVUCtx})), ++ grpc.WithChainStreamInterceptor(paceStream(statsHandler{getState: getState, getVUCtx: getVUCtx})), + } + } + ++// paceUnary and paceStream wait on the registered grpccapture pacer before the call starts. ++// They are interceptors, not TagRPC, because grpc-go stamps the call's BeginTime before ++// TagRPC: a wait there would be counted in grpc_req_duration. A wait cut short by the call's ++// context fails the call before anything is sent, and is recorded as a failed call. ++func paceUnary(h statsHandler) grpc.UnaryClientInterceptor { ++ return func( ++ ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, ++ invoker grpc.UnaryInvoker, opts ...grpc.CallOption, ++ ) error { ++ if err := grpccapture.Pace(ctx); err != nil { ++ return h.recordPaceFailure(ctx, method, err) ++ } ++ return invoker(ctx, method, req, reply, cc, opts...) ++ } ++} ++ ++func paceStream(h statsHandler) grpc.StreamClientInterceptor { ++ return func( ++ ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, ++ streamer grpc.Streamer, opts ...grpc.CallOption, ++ ) (grpc.ClientStream, error) { ++ if err := grpccapture.Pace(ctx); err != nil { ++ return nil, h.recordPaceFailure(ctx, method, err) ++ } ++ return streamer(ctx, desc, cc, method, opts...) ++ } ++} ++ ++// recordPaceFailure reports a call whose context ended while the pacer held it as the failed ++// call it is: the stats handler gets the TagRPC and End a started call gets, so one ++// grpc_req_duration sample is pushed with the context's status (DEADLINE_EXCEEDED or CANCELLED) ++// and the capture observer records the call. The call never started, so its duration is 0: the ++// pacing wait is not call latency. It returns the call's error. ++func (h statsHandler) recordPaceFailure(ctx context.Context, method string, err error) error { ++ callErr := status.FromContextError(err).Err() ++ if h.getState() == nil { ++ return callErr ++ } ++ ctx = h.TagRPC(ctx, &grpcstats.RPCTagInfo{FullMethodName: method}) ++ now := time.Now() ++ h.HandleRPC(ctx, &grpcstats.End{Client: true, BeginTime: now, EndTime: now, Error: callErr}) ++ return callErr ++} ++ + // Dial establish a gRPC connection. + func Dial(ctx context.Context, addr string, types *protoregistry.Types, options ...grpc.DialOption) (*Conn, error) { + conn, err := grpc.DialContext(ctx, addr, options...) //nolint:staticcheck +@@ -255,8 +303,13 @@ func (statsHandler) HandleConn(context.Context, grpcstats.ConnStats) { + } + + // TagRPC implements the grpcstats.Handler interface +-func (statsHandler) TagRPC(ctx context.Context, _ *grpcstats.RPCTagInfo) context.Context { +- // noop ++func (h statsHandler) TagRPC(ctx context.Context, info *grpcstats.RPCTagInfo) context.Context { ++ // xk6-load-toolkit: hand the call to a registered capture observer, which may attach its own state. ++ if c := grpccapture.Get(); c != nil { ++ if state := h.getState(); state != nil { ++ return c.TagRPC(ctx, info, state.VUIDGlobal) ++ } ++ } + return ctx + } + +@@ -303,6 +356,20 @@ func (h statsHandler) HandleRPC(ctx context.Context, stat grpcstats.RPCStats) { + }) + } + ++ // xk6-load-toolkit: after the switch, so the End stat's tags already carry the status. ++ if c := grpccapture.Get(); c != nil { ++ tagsAndMeta := stateRPC.tagsAndMeta ++ c.HandleRPC(ctx, stat, grpccapture.Call{ ++ VUID: state.VUIDGlobal, ++ Tags: func() map[string]string { ++ if tagsAndMeta == nil || tagsAndMeta.Tags == nil { ++ return map[string]string{} ++ } ++ return tagsAndMeta.Tags.Map() ++ }, ++ }) ++ } ++ + // (rogchap) Re-using --http-debug flag as gRPC is technically still HTTP + if state.Options.HTTPDebug.String != "" { + logger := state.Logger.WithField("source", "http-debug") +diff --git a/lib/netext/grpccapture/grpccapture.go b/lib/netext/grpccapture/grpccapture.go +new file mode 100644 +index 0000000..7215070 +--- /dev/null ++++ b/lib/netext/grpccapture/grpccapture.go +@@ -0,0 +1,83 @@ ++// Package grpccapture lets an xk6 extension observe the client-side stats of every gRPC call a ++// VU makes. It is the hook github.com/browserstack/xk6-load-toolkit uses to capture gRPC ++// request/response samples; it is added by that repository's patch, not by upstream k6. ++// ++// k6 calls the registered Handler from its gRPC stats handler. With nothing registered the ++// cost is one atomic load per stat. ++// ++// It also carries the pacer seam: k6's gRPC client interceptors call Pace before each unary ++// call and each stream open, which is how the toolkit's throughput limiter paces gRPC. ++package grpccapture ++ ++import ( ++ "context" ++ "sync/atomic" ++ ++ grpcstats "google.golang.org/grpc/stats" ++) ++ ++// Call identifies the VU making a gRPC call and the call's metric tags. ++type Call struct { ++ // VUID is the VU's global id (exec.vu.idInTest in a script). ++ VUID uint64 ++ // Tags returns the call's metric tags (name, method, service, scenario, ...). It is ++ // evaluated on demand, so a Handler that ignores a stat pays nothing for it. ++ Tags func() map[string]string ++} ++ ++// Handler observes gRPC calls. Both methods run on the calling VU's goroutine. ++type Handler interface { ++ // TagRPC runs when a call starts; the context it returns is the one HandleRPC receives ++ // for every stat of that call. ++ TagRPC(ctx context.Context, info *grpcstats.RPCTagInfo, vuID uint64) context.Context ++ // HandleRPC receives each stat of the call: OutHeader, OutPayload, InHeader, InPayload, ++ // InTrailer and End. ++ HandleRPC(ctx context.Context, stat grpcstats.RPCStats, call Call) ++} ++ ++type holder struct{ h Handler } ++ ++var current atomic.Pointer[holder] //nolint:gochecknoglobals ++ ++// Register installs h as the process's gRPC call observer; nil removes it. ++func Register(h Handler) { ++ if h == nil { ++ current.Store(nil) ++ return ++ } ++ current.Store(&holder{h: h}) ++} ++ ++// Get returns the registered Handler, or nil. ++func Get() Handler { ++ if p := current.Load(); p != nil { ++ return p.h ++ } ++ return nil ++} ++ ++// Pacer blocks until a gRPC call may start, or returns an error when ctx ends first. It runs ++// on the calling goroutine, once per unary call and once per stream open, before the call's ++// stats begin. ++type Pacer func(ctx context.Context) error ++ ++type pacerHolder struct{ p Pacer } ++ ++var pacer atomic.Pointer[pacerHolder] //nolint:gochecknoglobals ++ ++// RegisterPacer installs p as the process's gRPC pacer; nil removes it. ++func RegisterPacer(p Pacer) { ++ if p == nil { ++ pacer.Store(nil) ++ return ++ } ++ pacer.Store(&pacerHolder{p: p}) ++} ++ ++// Pace runs the registered Pacer; with none registered it returns nil at once. ++func Pace(ctx context.Context) error { ++ if h := pacer.Load(); h != nil { ++ return h.p(ctx) ++ } ++ return nil ++} diff --git a/patches/k6-grpc-deadline.patch b/patches/k6-grpc-deadline.patch new file mode 100644 index 0000000..4c64f5f --- /dev/null +++ b/patches/k6-grpc-deadline.patch @@ -0,0 +1,59 @@ +diff --git a/internal/js/modules/k6/grpc/client.go b/internal/js/modules/k6/grpc/client.go +index 0d16e56..16dd603 100644 +--- a/internal/js/modules/k6/grpc/client.go ++++ b/internal/js/modules/k6/grpc/client.go +@@ -227,7 +227,7 @@ func (c *Client) Connect(addr string, params sobek.Value) (bool, error) { + return false, fmt.Errorf("invalid grpc.connect() parameters: %w", err) + } + +- opts := grpcext.DefaultOptions(c.vu.State) ++ opts := grpcext.DefaultOptions(c.vu.State, c.vu.Context) + + var tcred credentials.TransportCredentials + if !p.IsPlaintext { +diff --git a/internal/lib/netext/grpcext/conn.go b/internal/lib/netext/grpcext/conn.go +index a266dc3..08fa6cc 100644 +--- a/internal/lib/netext/grpcext/conn.go ++++ b/internal/lib/netext/grpcext/conn.go +@@ -80,7 +80,7 @@ type Conn struct { + + // DefaultOptions generates an option set + // with common options for requests from a VU. +-func DefaultOptions(getState func() *lib.State) []grpc.DialOption { ++func DefaultOptions(getState func() *lib.State, getVUCtx func() context.Context) []grpc.DialOption { + dialer := func(ctx context.Context, addr string) (net.Conn, error) { + return getState().Dialer.DialContext(ctx, "tcp", addr) + } +@@ -89,7 +89,7 @@ func DefaultOptions(getState func() *lib.State) []grpc.DialOption { + grpc.WithBlock(), //nolint:staticcheck + grpc.FailOnNonTempDialError(true), //nolint:staticcheck + grpc.WithReturnConnectionError(), //nolint:staticcheck +- grpc.WithStatsHandler(statsHandler{getState: getState}), ++ grpc.WithStatsHandler(statsHandler{getState: getState, getVUCtx: getVUCtx}), + grpc.WithContextDialer(dialer), + } + } +@@ -240,6 +240,8 @@ func (c *Conn) Close() error { + + type statsHandler struct { + getState func() *lib.State ++ // The VU context, used to decide whether a finished RPC may still be pushed. ++ getVUCtx func() context.Context + } + + // TagConn implements the grpcstats.Handler interface +@@ -284,7 +286,13 @@ func (h statsHandler) HandleRPC(ctx context.Context, stat grpcstats.RPCStats) { + stateRPC.tagsAndMeta.SetSystemTagOrMeta(metrics.TagStatus, strconv.Itoa(int(status.Code(s.Error)))) + } + +- metrics.PushIfNotDone(ctx, state.Samples, metrics.Sample{ ++ // Push against the VU context, not the RPC context. A deadline cancels the RPC ++ // context, so PushIfNotDone(ctx, ...) silently dropped every DEADLINE_EXCEEDED sample. ++ pushCtx := ctx ++ if h.getVUCtx != nil { ++ pushCtx = h.getVUCtx() ++ } ++ metrics.PushIfNotDone(pushCtx, state.Samples, metrics.Sample{ + TimeSeries: metrics.TimeSeries{ + Metric: state.BuiltinMetrics.GRPCReqDuration, + Tags: stateRPC.tagsAndMeta.Tags, diff --git a/register.go b/register.go index 42a339f..bec1ee0 100644 --- a/register.go +++ b/register.go @@ -1,7 +1,8 @@ -// Package loadtoolkit is a k6 extension with three independently configured -// capabilities: an output that posts request, WebSocket and check rows as -// JSONEachRow, a request-rate limiter module and a tag filter module. All -// configuration comes from one JSON document in XK6_LOAD_TOOLKIT_CONFIG. +// Package loadtoolkit is a k6 extension with independently configured +// capabilities: an output that posts request, WebSocket, gRPC and check rows as +// JSONEachRow, a request-rate limiter module, a tag filter module and a gRPC +// call capture. All configuration comes from one JSON document in +// XK6_LOAD_TOOLKIT_CONFIG. // // The package exports nothing. k6 reaches the capabilities through the // registrations below (--out load-toolkit-sink, and the k6/x/load-toolkit/* JS @@ -13,6 +14,7 @@ import ( "go.k6.io/k6/v2/output" "github.com/browserstack/xk6-load-toolkit/internal/config" + "github.com/browserstack/xk6-load-toolkit/internal/grpccapture" "github.com/browserstack/xk6-load-toolkit/internal/sink" tagfilter "github.com/browserstack/xk6-load-toolkit/internal/tag-filter" "github.com/browserstack/xk6-load-toolkit/internal/throughput" @@ -25,8 +27,23 @@ func init() { cfg, err := config.Loaded() return newSink(cfg, err, params) }) - modules.Register(throughput.ModuleName, throughput.NewModule(config.Throughput)) + thr := throughput.NewModule(config.Throughput) + modules.Register(throughput.ModuleName, thr) modules.Register(tagfilter.ModuleName, tagfilter.NewModule(config.TagFilter)) + registerGRPCHooks(thr) +} + +// registerGRPCHooks connects the gRPC capabilities to the k6 gRPC hooks: the pacer only when a +// throughput section is present (otherwise each gRPC call pays nothing but one atomic load), +// and the capture only when a grpcCapture section is present. Without the hooks (a stock_k6 +// build) both are no-ops. +func registerGRPCHooks(thr *throughput.RootModule) { + if cfg, err := config.Throughput(); err == nil && cfg != nil { + thr.RegisterGRPCPacer() + } + if cfg, err := config.GRPCCapture(); err == nil { + grpccapture.Register(cfg) + } } // newSink builds the output from the configuration loaded at init. The check diff --git a/scripts/check-source-md.sh b/scripts/check-source-md.sh index 07f41ef..1506ce1 100755 --- a/scripts/check-source-md.sh +++ b/scripts/check-source-md.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # check-source-md.sh — fail when SOURCE.md no longer lists what the build uses: -# the manifest's k6 version, every pinned extension at its version, and the Go -# version CI builds with. +# the manifest's k6 version, every k6 patch, every pinned extension at its +# version, and the Go version CI builds with. # # scripts/check-source-md.sh [--manifest extensions.json] [--source SOURCE.md] [--ci .github/workflows/ci.yml] set -euo pipefail @@ -28,6 +28,15 @@ row_has() { grep -F -- "\`$1\`" "$SOURCE" | grep -qF -- "| $2 |"; } k6_version="$(jq -r '.k6Version' "$MANIFEST")" row_has "go.k6.io/k6/v2" "$k6_version" || fail "k6 $k6_version is not listed" +while IFS= read -r patch; do + [[ -n "$patch" ]] || continue + grep -qF -- "[\`$patch\`]" "$SOURCE" || fail "k6 patch $patch is not listed" + [[ -f "$(dirname "$MANIFEST")/$patch" ]] || fail "k6 patch $patch does not exist" +done < <(jq -r '(.k6Patches // [])[]' "$MANIFEST") +listed_patches="$(grep -cE '^\| \[`patches/[^`]+\.patch`\]' "$SOURCE" || true)" +declared_patches="$(jq '(.k6Patches // []) | length' "$MANIFEST")" +[[ "$listed_patches" -eq "$declared_patches" ]] || fail "lists $listed_patches k6 patches, the manifest declares $declared_patches" + while IFS='|' read -r module version; do row_has "$module" "$version" || fail "$module $version is not listed" done < <(jq -r '.extensions[] | select(.version) | "\(.module)|\(.version)"' "$MANIFEST") diff --git a/scripts/release-gate.sh b/scripts/release-gate.sh index 406d334..889ca57 100755 --- a/scripts/release-gate.sh +++ b/scripts/release-gate.sh @@ -6,7 +6,9 @@ # scripts/release-gate.sh --buildinfo --arch ... (pre-captured `go version -m` output) # # Fails unless: GOOS=linux, GOARCH= and CGO_ENABLED=0; go.k6.io/k6/v2 is -# linked at the manifest's k6Version; every "version" entry is linked at exactly +# linked at the manifest's k6Version, not replaced, or, when the manifest lists +# k6Patches, replaced by exactly the patched copy build.sh makes; every +# "version" entry is linked at exactly # that version and not replaced; every "repoPath" entry is linked; and no other # xk6-* module is linked, except ones k6 itself requires (read from k6's go.mod # via `go mod download`, or from --k6-gomod). @@ -39,11 +41,11 @@ errors=0 fail() { echo "release-gate: FAIL: $*" >&2; errors=$((errors + 1)); } setting() { printf '%s\n' "$info" | awk -F'\t' -v k="$1" '$2 == "build" && index($3, k "=") == 1 { print substr($3, length(k) + 2) }'; } -# " " for every linked dependency. +# " []" for every linked dependency. deps="$(printf '%s\n' "$info" | awk -F'\t' ' - $2 == "dep" { if (m != "") print m, v, r; m = $3; v = $4; r = 0; next } - $2 == "=>" { r = 1; next } - END { if (m != "") print m, v, r }')" + $2 == "dep" { if (m != "") print m, v, r, p; m = $3; v = $4; r = 0; p = ""; next } + $2 == "=>" { r = 1; p = $3; next } + END { if (m != "") print m, v, r, p }' | sed 's/ $//')" dep_line() { printf '%s\n' "$deps" | awk -v m="$1" '$1 == m { print; exit }'; } [[ "$(setting GOOS)" == "linux" ]] || fail "GOOS is '$(setting GOOS)', want linux" @@ -53,7 +55,15 @@ dep_line() { printf '%s\n' "$deps" | awk -v m="$1" '$1 == m { print; exit }'; } k6_want="$(jq -r '.k6Version // ""' "$MANIFEST")" k6_line="$(dep_line go.k6.io/k6/v2)" [[ -n "$k6_want" ]] || fail "manifest has no k6Version" -[[ "$k6_line" == "go.k6.io/k6/v2 $k6_want 0" ]] || fail "go.k6.io/k6/v2 linked as '${k6_line:-}', want $k6_want (not replaced)" +k6_patches="$(jq -r '(.k6Patches // []) | length' "$MANIFEST")" +if [[ "$k6_patches" -gt 0 ]]; then + # build.sh's fixed patch directory (see build.sh, k6Patches). + k6_patched_dir="/tmp/xk6-load-toolkit/k6-${k6_want}-patched" + [[ "$k6_line" == "go.k6.io/k6/v2 $k6_want 1 $k6_patched_dir" ]] || + fail "go.k6.io/k6/v2 linked as '${k6_line:-}', want $k6_want replaced by $k6_patched_dir (k6Patches)" +else + [[ "$k6_line" == "go.k6.io/k6/v2 $k6_want 0" ]] || fail "go.k6.io/k6/v2 linked as '${k6_line:-}', want $k6_want (not replaced)" +fi if [[ -z "$K6_GOMOD" && -n "$k6_want" ]]; then K6_GOMOD="$(go mod download -json "go.k6.io/k6/v2@$k6_want" | jq -r '.GoMod // ""')" || true diff --git a/scripts/release-gate_test.sh b/scripts/release-gate_test.sh index 3114a3c..3cdd7ca 100755 --- a/scripts/release-gate_test.sh +++ b/scripts/release-gate_test.sh @@ -19,6 +19,14 @@ edit() { perl -pe "$1" "$INFO" > "$tmp/info.txt"; echo "$tmp/info.txt"; } manifest() { jq "$1" "$MANIFEST" > "$tmp/manifest.json"; echo "$tmp/manifest.json"; } expect pass "recorded build matches the manifest" --buildinfo "$INFO" --arch amd64 +PATCHED='/tmp/xk6-load-toolkit/k6-v2.2.0-patched' +expect fail "k6Patches declared but k6 not replaced" \ + --buildinfo "$(edit 's|^(\tdep\tgo.k6.io/k6/v2\t.*)\n\t=>\t[^\n]*$|$1|; $_ = "" if m|^\t=>\t/tmp/xk6-load-toolkit/|')" --arch amd64 +expect fail "k6 replaced by another directory" \ + --buildinfo "$(edit "s|\Q$PATCHED\E|/tmp/other-k6|")" --arch amd64 +expect pass "no k6Patches: unreplaced k6 passes" \ + --buildinfo "$(edit '$_ = "" if m|^\t=>\t/tmp/xk6-load-toolkit/|')" --manifest "$(manifest 'del(.k6Patches)')" --arch amd64 +expect fail "no k6Patches: replaced k6 fails" --buildinfo "$INFO" --manifest "$(manifest 'del(.k6Patches)')" --arch amd64 expect fail "wrong arch" --buildinfo "$INFO" --arch arm64 expect fail "CGO enabled" --buildinfo "$(edit 's/CGO_ENABLED=0/CGO_ENABLED=1/')" --arch amd64 expect fail "built for another OS" --buildinfo "$(edit 's/GOOS=linux/GOOS=darwin/')" --arch amd64 From a4f166853620c9a5040960870114026cab12d4d2 Mon Sep 17 00:00:00 2001 From: Dheeren Date: Tue, 1 Dec 2026 13:28:16 +0530 Subject: [PATCH 03/11] release-gate fixture: re-recorded from a patched linux/amd64 build --- scripts/testdata/buildinfo-amd64.txt | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/scripts/testdata/buildinfo-amd64.txt b/scripts/testdata/buildinfo-amd64.txt index d088fe6..ea0a8a1 100644 --- a/scripts/testdata/buildinfo-amd64.txt +++ b/scripts/testdata/buildinfo-amd64.txt @@ -1,4 +1,4 @@ -k6-linux-amd64: go1.26.0 +k6-linux-amd64: go1.26.11 path k6 mod k6 (devel) dep buf.build/gen/go/gogo/protobuf/protocolbuffers/go v1.36.11-20240617172848-e1dbca2775a7.1 h1:redacted @@ -15,7 +15,7 @@ k6-linux-amd64: go1.26.0 dep github.com/PuerkitoBio/goquery v1.12.0 h1:redacted dep github.com/Soontao/goHttpDigestClient v0.0.0-20170320082612-6d28bb1415c5 h1:redacted dep github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da h1:redacted - dep github.com/andybalholm/brotli v1.2.2 h1:redacted + dep github.com/andybalholm/brotli v1.2.8 h1:redacted dep github.com/andybalholm/cascadia v1.3.3 h1:redacted dep github.com/beorn7/perks v1.0.1 h1:redacted dep github.com/brianvoe/gofakeit/v6 v6.28.0 h1:redacted @@ -84,7 +84,7 @@ k6-linux-amd64: go1.26.0 dep github.com/jhump/protoreflect v1.18.0 h1:redacted dep github.com/jhump/protoreflect/v2 v2.0.0-beta.1 h1:redacted dep github.com/json-iterator/go v1.1.12 h1:redacted - dep github.com/klauspost/compress v1.19.1 h1:redacted + dep github.com/klauspost/compress v1.20.4 h1:redacted dep github.com/knadh/koanf/maps v0.1.2 h1:redacted dep github.com/knadh/koanf/providers/confmap v1.0.0 h1:redacted dep github.com/knadh/koanf/v2 v2.3.5 h1:redacted @@ -128,7 +128,9 @@ k6-linux-amd64: go1.26.0 dep github.com/tidwall/match v1.1.1 h1:redacted dep github.com/tidwall/pretty v1.2.1 h1:redacted dep github.com/xhit/go-str2duration/v2 v2.1.0 h1:redacted - dep go.k6.io/k6/v2 v2.2.0 h1:redacted + dep go.k6.io/k6/v2 v2.2.0 + => /tmp/xk6-load-toolkit/k6-v2.2.0-patched (devel) + dep go.opentelemetry.io/auto/sdk v1.2.1 h1:redacted dep go.opentelemetry.io/collector v0.153.0 h1:redacted dep go.opentelemetry.io/collector/client v1.59.0 h1:redacted @@ -184,13 +186,13 @@ k6-linux-amd64: go1.26.0 dep go.uber.org/multierr v1.11.0 h1:redacted dep go.uber.org/zap v1.28.0 h1:redacted dep go.yaml.in/yaml/v3 v3.0.4 h1:redacted - dep golang.org/x/crypto v0.54.0 h1:redacted + dep golang.org/x/crypto v0.58.0 h1:redacted dep golang.org/x/crypto/x509roots/fallback v0.0.0-20260723152544-d701c51f7e4e h1:redacted - dep golang.org/x/net v0.57.0 h1:redacted - dep golang.org/x/sync v0.22.0 h1:redacted - dep golang.org/x/sys v0.47.0 h1:redacted - dep golang.org/x/term v0.45.0 h1:redacted - dep golang.org/x/text v0.40.0 h1:redacted + dep golang.org/x/net v0.62.0 h1:redacted + dep golang.org/x/sync v0.24.0 h1:redacted + dep golang.org/x/sys v0.49.0 h1:redacted + dep golang.org/x/term v0.47.0 h1:redacted + dep golang.org/x/text v0.43.0 h1:redacted dep golang.org/x/time v0.15.0 h1:redacted dep google.golang.org/genproto/googleapis/api v0.0.0-20260720211330-0afa2a65878a h1:redacted dep google.golang.org/genproto/googleapis/rpc v0.0.0-20260720211330-0afa2a65878a h1:redacted From c2df1d489a2fa140aa5d3e1ad522be446c514a96 Mon Sep 17 00:00:00 2001 From: Dheeren Date: Tue, 1 Dec 2026 13:34:27 +0530 Subject: [PATCH 04/11] grpcCapture: a regex that does not compile excludes nothing instead of rejecting the config --- README.md | 2 +- internal/grpccapture/capture_test.go | 4 ++-- internal/grpccapture/config.go | 15 ++++++++------- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 090ea5f..d62cc6d 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ whatever way the script imports `k6/net/grpc`. | `maxCapturingVUs` | how many VUs capture (default 20) | | `maxSuccess`, `maxErrors` | distinct successful / failing calls kept | | `maxErrorsPerScenario` | failing calls kept per scenario (default 13) | -| `exclude` | `[{ "pattern": "...", "regex": false }]`: OK calls never kept, matched on the call name or full method with one leading `/` trimmed | +| `exclude` | `[{ "pattern": "...", "regex": false }]`: OK calls never kept, matched on the call name or full method with one leading `/` trimmed; a regex that does not compile (RE2) is skipped | One sample is kept per (scenario, call name, status code). Messages are protojson, cut at 64 KB; each metadata map is cut at 16 KB. A file that cannot diff --git a/internal/grpccapture/capture_test.go b/internal/grpccapture/capture_test.go index 721bfda..b0fc112 100644 --- a/internal/grpccapture/capture_test.go +++ b/internal/grpccapture/capture_test.go @@ -107,7 +107,7 @@ func jsonOf(v any) string { func TestConfigValidateAndResolve(t *testing.T) { c := &Config{ File: "/x", TotalVUs: 40, VUSeed: -1, MaxSuccess: 10, MaxErrors: 15, - Exclude: []ExcludeRule{{Pattern: "/a.B/C"}, {Pattern: "^/pay\\.", Regex: true}}, + Exclude: []ExcludeRule{{Pattern: "/a.B/C"}, {Pattern: "(", Regex: true}, {Pattern: "^/pay\\.", Regex: true}}, } if err := c.Validate(); err != nil { t.Fatal(err) @@ -119,6 +119,7 @@ func TestConfigValidateAndResolve(t *testing.T) { if cfg.maxCapturingVUs != defaultMaxCapturingVUs || cfg.maxErrorsPerScenario != defaultMaxErrorsPerScenario { t.Fatalf("defaults %+v", cfg) } + // The regex that does not compile is skipped, not an error. if len(cfg.exclude) != 2 || cfg.exclude[0].pattern != "/a.B/C" || cfg.exclude[1].regex == nil { t.Fatalf("exclude %+v", cfg.exclude) } @@ -130,7 +131,6 @@ func TestConfigValidateAndResolve(t *testing.T) { "no file": {}, "negative cap": {File: "/x", MaxErrors: -1}, "empty pattern": {File: "/x", Exclude: []ExcludeRule{{}}}, - "bad regex": {File: "/x", Exclude: []ExcludeRule{{Pattern: "(", Regex: true}}}, } { if bad.Validate() == nil { t.Errorf("%s: want a validation error", name) diff --git a/internal/grpccapture/config.go b/internal/grpccapture/config.go index 1b2daa8..9612b25 100644 --- a/internal/grpccapture/config.go +++ b/internal/grpccapture/config.go @@ -51,7 +51,9 @@ type Config struct { } // ExcludeRule names calls by their row name or full method. A path rule compares with one -// leading "/" trimmed from both sides; a regex rule is tried with and without it. +// leading "/" trimmed from both sides; a regex rule is tried with and without it. A regex that +// does not compile (Go RE2 syntax) excludes nothing, so a rule written for another regex +// engine never stops a run. type ExcludeRule struct { Pattern string `json:"pattern"` Regex bool `json:"regex"` @@ -74,11 +76,6 @@ func (c *Config) Validate() error { if r.Pattern == "" { return fmt.Errorf("grpcCapture.exclude[%d].pattern: required", i) } - if r.Regex { - if _, err := regexp.Compile(r.Pattern); err != nil { - return fmt.Errorf("grpcCapture.exclude[%d].pattern: invalid regex: %w", i, err) - } - } } return nil } @@ -134,7 +131,11 @@ func resolve(c *Config) config { for _, r := range c.Exclude { rule := excludeRule{pattern: r.Pattern} if r.Regex { - rule.regex = regexp.MustCompile(r.Pattern) // validated + re, err := regexp.Compile(r.Pattern) + if err != nil { + continue + } + rule.regex = re } cfg.exclude = append(cfg.exclude, rule) } From dd4a2873a0b4423b6d213d84f6938b257ae9ea2d Mon Sep 17 00:00:00 2001 From: Dheeren Date: Tue, 1 Dec 2026 14:39:34 +0530 Subject: [PATCH 05/11] Hook code needs -tags k6patched (set by build.sh), so a plain go test ./... passes against stock k6 --- .github/workflows/ci.yml | 10 +++++----- README.md | 8 +++++--- SOURCE.md | 2 +- build.sh | 8 ++++++-- internal/grpccapture/capture_test.go | 4 ++-- internal/grpccapture/config.go | 5 +++-- internal/grpccapture/hook.go | 2 +- internal/grpccapture/hook_stock.go | 6 +++--- internal/throughput/grpc_hook.go | 2 +- internal/throughput/grpc_hook_stock.go | 2 +- register.go | 2 +- scripts/testdata/buildinfo-amd64.txt | 1 + 12 files changed, 30 insertions(+), 22 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1199932..12ce6ad 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,13 +26,13 @@ jobs: cache: true - name: gofmt run: test -z "$(gofmt -l .)" || { gofmt -l .; exit 1; } - # The gRPC hooks exist only in the patched k6 (see patches/), so the unit - # tests build against stock k6 with -tags stock_k6; the patched-build job - # compiles the hooked code. + # The gRPC hooks exist only in the patched k6 (see patches/); the code + # using them needs -tags k6patched, so these steps build against stock k6 + # and the patched-build job compiles the hooked code. - name: go vet - run: go vet -tags stock_k6 ./... + run: go vet ./... - name: go test - run: go test -tags stock_k6 -race -count=1 ./... + run: go test -race -count=1 ./... - name: Release gate tests run: bash scripts/release-gate_test.sh - name: SOURCE.md lists the pinned components diff --git a/README.md b/README.md index d62cc6d..6c2bbd8 100644 --- a/README.md +++ b/README.md @@ -379,8 +379,10 @@ default export: a script that writes `import { Client } from "k6/net/grpc"`, cannot recover the samples k6 drops for timed-out calls. The Go code that uses the hooks (`internal/grpccapture/hook.go`, -`internal/throughput/grpc_hook.go`) builds only against the patched k6; with -`-tags stock_k6` it compiles to no-ops, which is how the unit tests run. +`internal/throughput/grpc_hook.go`) builds only against the patched k6, with +`-tags k6patched`, which `build.sh` passes to xk6 (with xk6's default +`-trimpath` and `-ldflags=-s -w`). Without the tag it compiles to no-ops, so a +plain `go test ./...` runs against stock k6. ## Distribution @@ -440,7 +442,7 @@ interface; the root package hands it over. ## Tests ```sh -go test -tags stock_k6 ./... # unit tests, against stock k6 +go test ./... # unit tests, against stock k6 scripts/release-gate_test.sh GOOS=linux GOARCH=amd64 ./build.sh --output dist/k6 && \ scripts/release-gate.sh --binary dist/k6 --arch amd64 # compiles the hooked code diff --git a/SOURCE.md b/SOURCE.md index 92baa4c..eda2f2c 100644 --- a/SOURCE.md +++ b/SOURCE.md @@ -106,7 +106,7 @@ All in this repository at the same commit: | File | Role | |---|---| | [`extensions.json`](extensions.json) | The manifest: the k6 version, the k6 patches and every extension with its pinned version. | -| [`build.sh`](build.sh) | Applies the k6 patches to a copy of the pinned k6 source at `/tmp/xk6-load-toolkit/k6--patched`, turns the manifest into `xk6 build --k6-version … --with @ … --replace go.k6.io/k6/v2=` and runs it with CGO off. | +| [`build.sh`](build.sh) | Applies the k6 patches to a copy of the pinned k6 source at `/tmp/xk6-load-toolkit/k6--patched`, turns the manifest into `xk6 build --k6-version … --with @ … --replace go.k6.io/k6/v2= --build-flags -trimpath --build-flags "-ldflags=-s -w" --build-flags -tags=k6patched` and runs it with CGO off. | | [`patches/`](patches) | The k6 patches listed above. | | [`scripts/release-gate.sh`](scripts/release-gate.sh) | Reads the binary's `go version -m` output and fails unless every pin above is linked at exactly its version, and k6 is replaced by exactly the patched copy. | | This file | The builder stage below, the toolchain pins and the component list. | diff --git a/build.sh b/build.sh index 6edb5f8..e3736d5 100755 --- a/build.sh +++ b/build.sh @@ -11,8 +11,9 @@ # "k6Patches" (optional) lists repo-relative patch files applied to the k6 source # before the build: the pinned k6 module is fetched through the Go module proxy, # copied to a fixed directory, patched with `git apply`, and handed to xk6 with -# --replace. A patch that no longer applies (k6 version drift) fails the build, -# and so does a binary that was not linked against the patched copy. +# --replace, with -tags k6patched so the code that uses the patched k6's hooks +# is compiled in. A patch that no longer applies (k6 version drift) fails the +# build, and so does a binary that was not linked against the patched copy. # # Each manifest entry has exactly one of: # "repoPath": a directory relative to --repo-root -> --with = @@ -115,6 +116,9 @@ if [[ ${#K6_PATCHES[@]} -gt 0 ]]; then echo "[build] patched k6 ${K6_VERSION} with ${patch_path}" done REPLACE_ARGS=(--replace "${K6_MODULE}=${PATCHED_K6_DIR}") + # The code that uses the patched k6's hooks builds only with -tags k6patched. --build-flags + # replaces xk6's defaults, so they are repeated here unchanged. + REPLACE_ARGS+=(--build-flags -trimpath --build-flags "-ldflags=-s -w" --build-flags -tags=k6patched) fi mkdir -p "$(dirname "$OUTPUT")" diff --git a/internal/grpccapture/capture_test.go b/internal/grpccapture/capture_test.go index b0fc112..081f3b5 100644 --- a/internal/grpccapture/capture_test.go +++ b/internal/grpccapture/capture_test.go @@ -21,8 +21,8 @@ import ( "google.golang.org/protobuf/types/known/structpb" ) -// Run with `go test -tags stock_k6 ./...` against stock k6, or plain `go test` against the -// patched k6 that build.sh produces. +// Plain `go test ./...` runs against stock k6 (the recorder is tested directly; hook.go needs +// the patched k6 and the k6patched tag, which only build.sh sets). func baseEnv() *Config { return &Config{File: "/tmp/unused", TotalVUs: 1, MaxSuccess: 20, MaxErrors: 30} diff --git a/internal/grpccapture/config.go b/internal/grpccapture/config.go index 9612b25..c6acb42 100644 --- a/internal/grpccapture/config.go +++ b/internal/grpccapture/config.go @@ -4,8 +4,9 @@ // // It observes calls through the go.k6.io/k6/v2/lib/netext/grpccapture hook that // patches/k6-grpc-capture.patch adds to k6's gRPC stats handler, so the recording part -// builds only against the patched k6 that build.sh produces (see hook.go). Built with -// -tags stock_k6 the capability compiles to a no-op, which is how the unit tests run. +// builds only against the patched k6 that build.sh produces, which passes -tags k6patched (see +// hook.go). Without that tag the capability compiles to a no-op, which is how a plain +// `go test ./...` runs against stock k6. // // What it keeps: calls from at most maxCapturingVUs VUs, chosen by a seeded shuffle of the // run's VU ids; at most one sample per (scenario, call name, status code); at most diff --git a/internal/grpccapture/hook.go b/internal/grpccapture/hook.go index f585ab0..0638ee9 100644 --- a/internal/grpccapture/hook.go +++ b/internal/grpccapture/hook.go @@ -1,4 +1,4 @@ -//go:build !stock_k6 +//go:build k6patched package grpccapture diff --git a/internal/grpccapture/hook_stock.go b/internal/grpccapture/hook_stock.go index be5974c..2571091 100644 --- a/internal/grpccapture/hook_stock.go +++ b/internal/grpccapture/hook_stock.go @@ -1,9 +1,9 @@ -//go:build stock_k6 +//go:build !k6patched package grpccapture -// HooksAvailable reports whether this binary carries the k6 gRPC hooks. A stock_k6 build -// (the unit tests) has none. +// HooksAvailable reports whether this binary carries the k6 gRPC hooks. A build without the +// k6patched tag (stock k6, the unit tests) has none. const HooksAvailable = false // Register is a no-op without the k6 gRPC hooks. diff --git a/internal/throughput/grpc_hook.go b/internal/throughput/grpc_hook.go index 2df0355..2d4186a 100644 --- a/internal/throughput/grpc_hook.go +++ b/internal/throughput/grpc_hook.go @@ -1,4 +1,4 @@ -//go:build !stock_k6 +//go:build k6patched package throughput diff --git a/internal/throughput/grpc_hook_stock.go b/internal/throughput/grpc_hook_stock.go index f294e52..cb95453 100644 --- a/internal/throughput/grpc_hook_stock.go +++ b/internal/throughput/grpc_hook_stock.go @@ -1,4 +1,4 @@ -//go:build stock_k6 +//go:build !k6patched package throughput diff --git a/register.go b/register.go index bec1ee0..ebed8ac 100644 --- a/register.go +++ b/register.go @@ -35,7 +35,7 @@ func init() { // registerGRPCHooks connects the gRPC capabilities to the k6 gRPC hooks: the pacer only when a // throughput section is present (otherwise each gRPC call pays nothing but one atomic load), -// and the capture only when a grpcCapture section is present. Without the hooks (a stock_k6 +// and the capture only when a grpcCapture section is present. Without the hooks (a build without -tags k6patched // build) both are no-ops. func registerGRPCHooks(thr *throughput.RootModule) { if cfg, err := config.Throughput(); err == nil && cfg != nil { diff --git a/scripts/testdata/buildinfo-amd64.txt b/scripts/testdata/buildinfo-amd64.txt index ea0a8a1..a6b20d2 100644 --- a/scripts/testdata/buildinfo-amd64.txt +++ b/scripts/testdata/buildinfo-amd64.txt @@ -205,6 +205,7 @@ k6-linux-amd64: go1.26.11 dep lukechampine.com/frand v1.4.2 h1:redacted build -buildmode=exe build -compiler=gc + build -tags=k6patched build -trimpath=true build CGO_ENABLED=0 build GOARCH=amd64 From a33006bbd2f4ba2fbeb53fe6cc7abcb48a252a67 Mon Sep 17 00:00:00 2001 From: Dheeren Date: Tue, 1 Dec 2026 14:43:43 +0530 Subject: [PATCH 06/11] release-gate: a patched k6 must be built with -tags k6patched, so the gRPC hook code cannot be left out silently --- scripts/release-gate.sh | 7 ++++++- scripts/release-gate_test.sh | 4 ++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/scripts/release-gate.sh b/scripts/release-gate.sh index 889ca57..633ba53 100755 --- a/scripts/release-gate.sh +++ b/scripts/release-gate.sh @@ -7,7 +7,8 @@ # # Fails unless: GOOS=linux, GOARCH= and CGO_ENABLED=0; go.k6.io/k6/v2 is # linked at the manifest's k6Version, not replaced, or, when the manifest lists -# k6Patches, replaced by exactly the patched copy build.sh makes; every +# k6Patches, replaced by exactly the patched copy build.sh makes and built with +# -tags k6patched; every # "version" entry is linked at exactly # that version and not replaced; every "repoPath" entry is linked; and no other # xk6-* module is linked, except ones k6 itself requires (read from k6's go.mod @@ -61,6 +62,10 @@ if [[ "$k6_patches" -gt 0 ]]; then k6_patched_dir="/tmp/xk6-load-toolkit/k6-${k6_want}-patched" [[ "$k6_line" == "go.k6.io/k6/v2 $k6_want 1 $k6_patched_dir" ]] || fail "go.k6.io/k6/v2 linked as '${k6_line:-}', want $k6_want replaced by $k6_patched_dir (k6Patches)" + # Without the tag the code that uses the patched k6's hooks compiles to no-ops (capture and + # gRPC pacing silently off), so a patched binary must carry it. + [[ ",$(setting -tags)," == *",k6patched,"* ]] || + fail "built without -tags k6patched (got '$(setting -tags)'); the gRPC hook code would be left out" else [[ "$k6_line" == "go.k6.io/k6/v2 $k6_want 0" ]] || fail "go.k6.io/k6/v2 linked as '${k6_line:-}', want $k6_want (not replaced)" fi diff --git a/scripts/release-gate_test.sh b/scripts/release-gate_test.sh index 3cdd7ca..55b29f2 100755 --- a/scripts/release-gate_test.sh +++ b/scripts/release-gate_test.sh @@ -22,6 +22,10 @@ expect pass "recorded build matches the manifest" --buildinfo "$INFO" --arch amd PATCHED='/tmp/xk6-load-toolkit/k6-v2.2.0-patched' expect fail "k6Patches declared but k6 not replaced" \ --buildinfo "$(edit 's|^(\tdep\tgo.k6.io/k6/v2\t.*)\n\t=>\t[^\n]*$|$1|; $_ = "" if m|^\t=>\t/tmp/xk6-load-toolkit/|')" --arch amd64 +expect fail "k6Patches declared but built without -tags k6patched" \ + --buildinfo "$(edit '$_ = "" if m|^\tbuild\t-tags=|')" --arch amd64 +expect fail "k6Patches declared but another tag set" \ + --buildinfo "$(edit 's|^(\tbuild\t-tags=)k6patched|${1}other|')" --arch amd64 expect fail "k6 replaced by another directory" \ --buildinfo "$(edit "s|\Q$PATCHED\E|/tmp/other-k6|")" --arch amd64 expect pass "no k6Patches: unreplaced k6 passes" \ From e652aac23b79dd34c9d9cc2a367771697e80d271 Mon Sep 17 00:00:00 2001 From: Dheeren Date: Tue, 1 Dec 2026 17:13:53 +0530 Subject: [PATCH 07/11] sink: split gRPC stream rows by VU when a column reads computed:vus The stream key held explicit tag and metadata sources only, so stream samples from two VUs summed into one row whose vus column showed only one of them. A computed value now names the sample tags it reads, and the stream key includes them. --- internal/sink/columns.go | 5 ++++- internal/sink/grpc.go | 4 ++++ internal/sink/grpc_test.go | 13 ++++++++----- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/internal/sink/columns.go b/internal/sink/columns.go index 2f0e3dc..b2f294d 100644 --- a/internal/sink/columns.go +++ b/internal/sink/columns.go @@ -63,6 +63,9 @@ type builtin struct { str func(*rowView) string num func(*rowView) int64 boolean func(*rowView) bool + // tags names the sample tags the value reads that the gRPC stream key does not already + // carry, so summed stream rows are split wherever the rendered value would differ. + tags []string } // requestBuiltins are the computed values available to sink.columns. Each one @@ -81,7 +84,7 @@ var requestBuiltins = map[string]builtin{ "url": {kind: kindString, str: rowURL}, "requestName": {kind: kindString, str: requestName}, "group": {kind: kindString, str: func(v *rowView) string { return v.tags["group"] }}, - "vus": {kind: kindInt, num: func(v *rowView) int64 { + "vus": {kind: kindInt, tags: []string{"vu"}, num: func(v *rowView) int64 { if v.ws { return 0 } diff --git a/internal/sink/grpc.go b/internal/sink/grpc.go index 78f51c9..9594db6 100644 --- a/internal/sink/grpc.go +++ b/internal/sink/grpc.go @@ -79,6 +79,10 @@ func newGRPCEngine(c *CorrelationConfig, cols columns) *grpcEngine { tags[s.tag] = struct{}{} case s.isMeta: meta[s.meta] = struct{}{} + case s.builtin != nil: + for _, t := range s.builtin.tags { + tags[t] = struct{}{} + } } } } diff --git a/internal/sink/grpc_test.go b/internal/sink/grpc_test.go index e7cea4d..dc2cbef 100644 --- a/internal/sink/grpc_test.go +++ b/internal/sink/grpc_test.go @@ -2,6 +2,7 @@ package sink import ( "encoding/json" + "fmt" "path/filepath" "sort" "strings" @@ -394,21 +395,23 @@ func TestGRPC_StreamBucketIsConfigurable(t *testing.T) { } } -// Samples that differ on a tag a column reads sum into separate rows, so a -// summed row never mixes two values of that column. +// Samples that differ on a tag a column reads, directly or through a computed +// value (computed:vus reads the vu tag), sum into separate rows, so a summed +// row never mixes two values of that column. func TestGRPC_StreamKeyIncludesColumnTags(t *testing.T) { reg := metrics.NewRegistry() b := newGRPCBuffer(t, 0) at := time.Unix(1_700_000_001, 0) b.add(mkSample(reg, grpcStreams, callTags(map[string]string{"instance": "a"}), at, 1)) b.add(mkSample(reg, grpcStreams, callTags(map[string]string{"instance": "b"}), at, 1)) + b.add(mkSample(reg, grpcStreams, callTags(map[string]string{"instance": "b"}), at, 1)) b.add(mkSample(reg, grpcStreams, callTags(map[string]string{"instance": "b", "vu": "9"}), at, 1)) got := map[string]int64{} for _, r := range decodeGRPCRows(t, drainNow(b)) { - got[r.Instance] = r.StreamsOpened + got[fmt.Sprintf("%s/%d", r.Instance, r.VUs)] = r.StreamsOpened } - if len(got) != 2 || got["a"] != 1 || got["b"] != 2 { - t.Fatalf("streamsOpened by instance = %v, want {a:1, b:2}", got) + if len(got) != 3 || got["a/3"] != 1 || got["b/3"] != 2 || got["b/9"] != 1 { + t.Fatalf("streamsOpened by instance/vus = %v, want {a/3:1, b/3:2, b/9:1}", got) } } From e7f3a437a00792099389f6d51cf4b9ae214a7a40 Mon Sep 17 00:00:00 2001 From: Dheeren Date: Wed, 2 Dec 2026 11:02:13 +0530 Subject: [PATCH 08/11] grpccapture: describe the capture file and stderr in generic terms Comments only: drop references to a specific runner layout, an internal log pipeline, an internal script and a test-case id. --- internal/grpccapture/capture.go | 7 +++---- internal/grpccapture/capture_test.go | 6 +++--- internal/grpccapture/config.go | 2 +- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/internal/grpccapture/capture.go b/internal/grpccapture/capture.go index 546c822..8d2769b 100644 --- a/internal/grpccapture/capture.go +++ b/internal/grpccapture/capture.go @@ -96,10 +96,9 @@ func newRecorder(cfg config) *recorder { } // openCaptureFile opens the pre-created capture file for appending. It never creates the file -// and never follows a symlink: the logs directory is world-writable and sticky, and only the -// root-created file is trusted. +// and never follows a symlink: the caller creates the file, and only that file is trusted. func openCaptureFile(path string) (io.Writer, error) { - return os.OpenFile(path, os.O_WRONLY|os.O_APPEND|syscall.O_NOFOLLOW, 0) //nolint:gosec // fixed runner path + return os.OpenFile(path, os.O_WRONLY|os.O_APPEND|syscall.O_NOFOLLOW, 0) //nolint:gosec // path supplied by the caller } // full reports whether both caps are reached; a full recorder ignores every later call. @@ -283,7 +282,7 @@ func (r *recorder) write(s sample) { out, openErr := r.open(r.cfg.path) if openErr != nil { r.broken = true - // No path, no data: the reason only (k6's stderr reaches the customer log). + // No path, no data: the reason only (stderr may be shown to users). fmt.Fprintf(os.Stderr, "[grpc-capture] capture file unavailable; gRPC capture off for this run\n") return } diff --git a/internal/grpccapture/capture_test.go b/internal/grpccapture/capture_test.go index 081f3b5..f7d1a75 100644 --- a/internal/grpccapture/capture_test.go +++ b/internal/grpccapture/capture_test.go @@ -161,7 +161,7 @@ func TestCapturesAnOKAndAnErrorCall(t *testing.T) { if ok.Response.Message == nil || *ok.Response.Message != `{"ok":true}` || ok.Response.Error != nil { t.Fatalf("response %+v", ok.Response) } - // Metadata is written as received; k6ReqToClickhouse.js redacts it before publishing. + // Metadata is written as received; redact it before it leaves the machine. if ok.Request.Metadata["tenant"] != "acme" || ok.Response.Headers["content-type"] != "application/grpc" || ok.Response.Trailers["grpc-status"] != "0" { t.Fatalf("metadata %+v / %+v", ok.Request, ok.Response) @@ -250,8 +250,8 @@ func TestExclusionDropsOnlyOKCalls(t *testing.T) { } } -// TC-026: k6 names a call "/pkg.Service/Method"; customers (and the JMeter path) write the -// rule without the leading slash. Either spelling must match either side. +// k6 names a call "/pkg.Service/Method"; rules are usually written without the leading +// slash. Either spelling must match either side. func TestExcludeRuleMatchesWithOrWithoutLeadingSlash(t *testing.T) { exact := func(p string) excludeRule { return excludeRule{pattern: p} } re := func(p string) excludeRule { return excludeRule{pattern: p, regex: regexp.MustCompile(p)} } diff --git a/internal/grpccapture/config.go b/internal/grpccapture/config.go index c6acb42..58263be 100644 --- a/internal/grpccapture/config.go +++ b/internal/grpccapture/config.go @@ -38,7 +38,7 @@ type Config struct { // TotalVUs is the number of VU ids (1..TotalVUs) capturing VUs are chosen from. TotalVUs int `json:"totalVUs"` // VUSeed seeds the shuffle that picks the capturing VUs; it is truncated to 32 bits, as - // JavaScript's `seed >>> 0` does, so a JS capturer with the same seed picks the same VUs. + // JavaScript's `seed >>> 0` does, so any implementation of this shuffle picks the same VUs. VUSeed int64 `json:"vuSeed"` // MaxCapturingVUs caps how many VUs capture (default 20). MaxCapturingVUs int `json:"maxCapturingVUs"` From 924bf748198eff0701dfc063342a6b989ecd4a16 Mon Sep 17 00:00:00 2001 From: Dheeren Date: Wed, 2 Dec 2026 18:37:42 +0530 Subject: [PATCH 09/11] throughput: do not charge gRPC server reflection against the rate The gRPC pacer took a grant for every stream open, including the server-reflection stream connect({ reflect: true }) opens. That stream is connection setup, not a call, and the sink writes no row for it. A script that connects with reflection every iteration and then makes two calls spent three grants per two calls, so a gRPC-only throughput run delivered about 2/3 of its target at every stage (measured 33.4 and 51.3 calls/s on 50 and 80 rps holds). HTTP and proto-file gRPC scripts open no reflection stream and were unaffected. The k6 patch now passes the call's full method name to the pacer (Pacer(ctx, method)), and GRPCPacer skips the grpc.reflection.v1 and v1alpha ServerReflection services. A new test simulates a gRPC-only ramp with 80 VUs on a fake clock and asserts the calls in every stage match a greedy driver of the same limiter; its control, charging reflection, reproduces the 2/3 shortfall. --- README.md | 5 +- SOURCE.md | 2 +- internal/throughput/grpc.go | 40 +++++++- internal/throughput/grpc_test.go | 157 +++++++++++++++++++++++++++++-- patches/k6-grpc-capture.patch | 12 +-- 5 files changed, 196 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 6c2bbd8..c7ceaf9 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,8 @@ gRPC calls are paced too, with no script change: when the section is present, the limiter is registered with the k6 gRPC hooks (see [k6 patches](#k6-patches)), and each unary call and each stream open takes one grant from the same limiter before it starts, so HTTP and gRPC share one rate. Messages inside a stream take -nothing. The wait runs on the call's own context, so a call whose deadline passes +nothing, and neither does the server-reflection stream `connect({ reflect: true })` +opens: it is connection setup, not a call, and the sink writes no row for it. The wait runs on the call's own context, so a call whose deadline passes while it waits fails with `DEADLINE_EXCEEDED` and is recorded as a failed call. ### `tagFilter` @@ -370,7 +371,7 @@ the patched copy. Bumping `k6Version` means re-checking every patch. | Patch | Why | |---|---| | `k6-grpc-deadline.patch` | stock k6 drops the `grpc_req_duration` sample of a call that ends with `DEADLINE_EXCEEDED` (the deadline cancels the context the sample is pushed with); the patch pushes it against the VU context, so timed-out calls are counted | -| `k6-grpc-capture.patch` | adds `lib/netext/grpccapture`: a hook an extension registers to observe every gRPC call's stats (used by `grpcCapture`) and a pacer called before each unary call and stream open (used by `throughput`) | +| `k6-grpc-capture.patch` | adds `lib/netext/grpccapture`: a hook an extension registers to observe every gRPC call's stats (used by `grpcCapture`) and a pacer called with the method name before each unary call and stream open (used by `throughput`) | The hooks live in k6's gRPC client rather than in a JavaScript wrapper around `k6/net/grpc`, because a wrapper only sees calls made through the module's diff --git a/SOURCE.md b/SOURCE.md index eda2f2c..5366098 100644 --- a/SOURCE.md +++ b/SOURCE.md @@ -47,7 +47,7 @@ these files. | Patch | What it changes | |---|---| | [`patches/k6-grpc-deadline.patch`](patches/k6-grpc-deadline.patch) | Pushes a finished gRPC call's `grpc_req_duration` sample against the VU context instead of the call's own, so calls that end with `DEADLINE_EXCEEDED` are recorded (stock k6 drops them, because the deadline cancels the call's context). | -| [`patches/k6-grpc-capture.patch`](patches/k6-grpc-capture.patch) | Adds the `lib/netext/grpccapture` package: a hook an extension can register to observe every gRPC call's stats (used by the `grpcCapture` capability) and a pacer called before each unary call and stream open (used by the throughput limiter). With nothing registered each call pays one atomic load. | +| [`patches/k6-grpc-capture.patch`](patches/k6-grpc-capture.patch) | Adds the `lib/netext/grpccapture` package: a hook an extension can register to observe every gRPC call's stats (used by the `grpcCapture` capability) and a pacer called with the method name before each unary call and stream open (used by the throughput limiter). With nothing registered each call pays one atomic load. | ### Third-party extensions (15, pinned in `extensions.json`) diff --git a/internal/throughput/grpc.go b/internal/throughput/grpc.go index 7e7a143..e3e3326 100644 --- a/internal/throughput/grpc.go +++ b/internal/throughput/grpc.go @@ -1,10 +1,21 @@ package throughput -import "context" +import ( + "context" + "strings" +) // GRPCPacer is what k6's gRPC client interceptors call before each unary call and each stream -// open (the hook patches/k6-grpc-capture.patch adds): one grant from the limiter the JS module -// uses, so HTTP and gRPC share one target. Messages inside a stream take nothing. +// open (the hook patches/k6-grpc-capture.patch adds), with the call's full method name: one +// grant from the limiter the JS module uses, so HTTP and gRPC share one target. Messages inside +// a stream take nothing. +// +// Server reflection takes nothing either. connect({ reflect: true }) opens a reflection stream +// to fetch the service descriptors; it is connection setup, not a call the script makes, and the +// sink writes no row for it. Charging it spent a grant per connect: a script that connects with +// reflection every iteration and then makes two calls delivered two calls per three grants, so +// a gRPC-only run reached about 2/3 of its target at every stage (HTTP and proto-file scripts +// were unaffected, as they open no reflection stream). // // The wait runs on the call's own context, so it ends early, without a grant, when the run // stops or the call's deadline passes; k6 then fails the call before anything is sent and @@ -14,8 +25,11 @@ import "context" // // No limiter (section absent) or a misconfigured one is a no-op here: the JS module's // _enabled() throws on a bad configuration, which fails the run before any gRPC call is made. -func (r *RootModule) GRPCPacer() func(context.Context) error { - return func(ctx context.Context) error { +func (r *RootModule) GRPCPacer() func(ctx context.Context, method string) error { + return func(ctx context.Context, method string) error { + if isReflectionMethod(method) { + return nil + } l, err := r.shared() if err != nil || l == nil { return nil @@ -23,3 +37,19 @@ func (r *RootModule) GRPCPacer() func(context.Context) error { return l.Acquire(ctx) } } + +// reflectionServices are the gRPC server-reflection services, as full method-name prefixes +// ("/./"). k6 calls v1 and falls back to v1alpha. +var reflectionServices = [...]string{ + "/grpc.reflection.v1.ServerReflection/", + "/grpc.reflection.v1alpha.ServerReflection/", +} + +func isReflectionMethod(method string) bool { + for _, p := range reflectionServices { + if strings.HasPrefix(method, p) { + return true + } + } + return false +} diff --git a/internal/throughput/grpc_test.go b/internal/throughput/grpc_test.go index be9fd56..abb5b10 100644 --- a/internal/throughput/grpc_test.go +++ b/internal/throughput/grpc_test.go @@ -22,8 +22,8 @@ func TestGRPCPacerSharesTheModuleLimiter(t *testing.T) { l.EnableTrace() pace := r.GRPCPacer() - for i := 0; i < 3; i++ { // e.g. two unary calls and one stream open - if err := pace(context.Background()); err != nil { + for _, m := range []string{unaryMethod, unaryMethod, "/sut.v1.LoadSut/Stream"} { // two unary calls, one stream open + if err := pace(context.Background(), m); err != nil { t.Fatal(err) } } @@ -47,7 +47,7 @@ func TestGRPCPacerWithoutThroughputIsANoOp(t *testing.T) { pace := rootWith(nil, nil).GRPCPacer() start := time.Now() for i := 0; i < 100; i++ { - if err := pace(context.Background()); err != nil { + if err := pace(context.Background(), unaryMethod); err != nil { t.Fatal(err) } } @@ -63,7 +63,7 @@ func TestGRPCPacerIgnoresAMisconfiguredSection(t *testing.T) { if _, err := r.shared(); err == nil { t.Fatal("shared() hid the load error") } - if err := r.GRPCPacer()(context.Background()); err != nil { + if err := r.GRPCPacer()(context.Background(), unaryMethod); err != nil { t.Fatalf("pacer returned %v for a misconfigured section, want nil", err) } } @@ -75,13 +75,13 @@ func TestGRPCPacerStopsWaitingWhenTheCallEnds(t *testing.T) { l, _ := r.shared() l.EnableTrace() pace := r.GRPCPacer() - if err := pace(context.Background()); err != nil { // fills the window + if err := pace(context.Background(), unaryMethod); err != nil { // fills the window t.Fatal(err) } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) defer cancel() done := make(chan error, 1) - go func() { done <- pace(ctx) }() + go func() { done <- pace(ctx, unaryMethod) }() select { case err := <-done: if err == nil { @@ -94,3 +94,148 @@ func TestGRPCPacerStopsWaitingWhenTheCallEnds(t *testing.T) { t.Fatalf("ledger has %d grants after a cancelled wait, want 1", got) } } + +const unaryMethod = "/sut.v1.LoadSut/Unary" + +// The server-reflection stream connect({ reflect: true }) opens is connection setup: it takes no +// grant, in either reflection version, while every other method does. +func TestGRPCPacerDoesNotChargeReflection(t *testing.T) { + r := rootWith(&Config{PodRPS: 50}, nil) + l, _ := r.shared() + l.EnableTrace() + pace := r.GRPCPacer() + for _, m := range []string{ + "/grpc.reflection.v1.ServerReflection/ServerReflectionInfo", + "/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo", + } { + if err := pace(context.Background(), m); err != nil { + t.Fatal(err) + } + } + if got := len(l.Trace()); got != 0 { + t.Fatalf("reflection took %d grants, want 0", got) + } + // A user service whose name merely contains "reflection" is a call like any other. + for _, m := range []string{unaryMethod, "/acme.reflection.v1.Mirror/Get", "/grpc.reflection.v1.ServerReflectionX/Info"} { + if err := pace(context.Background(), m); err != nil { + t.Fatal(err) + } + } + if got := len(l.Trace()); got != 3 { + t.Fatalf("3 non-reflection calls took %d grants, want 3", got) + } +} + +// errWouldWait stands in for the limiter's sleep in the simulation below, so a refused pace +// returns at once and the VU retries on the next tick of the shared fake clock. +var errWouldWait = errors.New("would wait") + +// simulateGRPCOnlyRamp runs a gRPC-only script against a schedule on a fake 1ms clock: 80 VUs +// ramped in over 5s (the runner's ramping-vus shape), each iteration connect({ reflect: true }), +// two unary calls of 100ms, then sleep(1). It returns the unary calls started in each segment. +func simulateGRPCOnlyRamp(t *testing.T, segs []Segment, pace func(context.Context, string) error, clk *fakeClock) []int { + t.Helper() + const ( + vus = 80 + rampVUs = 5 * time.Second + callTime = 100 * time.Millisecond + thinking = time.Second + ) + type op struct { + method string // paced before the step; empty for none + hold time.Duration // then the VU is busy this long + } + iteration := []op{ + {"/grpc.reflection.v1.ServerReflection/ServerReflectionInfo", 0}, + {unaryMethod, callTime}, + {unaryMethod, callTime}, + {"", thinking}, + } + type vu struct { + ready time.Time + next int + } + pool := make([]vu, vus) + for i := range pool { + pool[i].ready = testT0.Add(rampVUs * time.Duration(i) / vus) + } + s := newSchedule(segs) + calls := make([]int, len(segs)) + end := testT0.Add(time.Duration(s.totalNs)) + for tick := 0; ; tick++ { + if clk.t = testT0.Add(time.Duration(tick) * time.Millisecond); !clk.t.Before(end) { + break + } + for k := range pool { // rotate who asks first, as the limiter's turn token would + v := &pool[(k+tick)%vus] + for !v.ready.After(clk.t) { + o := iteration[v.next] + if o.method != "" { + if err := pace(context.Background(), o.method); err != nil { + if !errors.Is(err, errWouldWait) { + t.Fatal(err) + } + break + } + if o.method == unaryMethod { + calls[s.seg(clk.t.Sub(testT0).Nanoseconds())]++ + } + } + v.ready = clk.t.Add(o.hold) + v.next = (v.next + 1) % len(iteration) + } + } + } + return calls +} + +// A gRPC-only throughput ramp 0->50 (10s), hold 50 (10s), 50->80 (10s), hold 80 (10s), +// 80->0 (10s), with a script that connects with reflection every iteration, was measured at +// 33.4 and 51.3 calls/s on the holds — 2/3 of the target, because the reflection stream took +// a grant per iteration. The calls a gRPC-only script makes must track each stage +// the way a greedy (unlimited-VU) driver of the same limiter does. +func TestGRPCOnlyRampTracksEveryStage(t *testing.T) { + segs := []Segment{{0, 50, 10}, {50, 50, 10}, {50, 80, 10}, {80, 80, 10}, {80, 0, 10}} + newSim := func() (*ScheduleLimiter, *fakeClock) { + clk := &fakeClock{} + l := newTestScheduleLimiter(t, segs, clk) + l.sleep = func(context.Context, time.Duration) error { return errWouldWait } + return l, clk + } + + // What the limiter itself lets through per stage: a greedy driver on the same schedule. + gl, gclk := newSim() + ceiling := make([]int, len(segs)) + for _, g := range greedy(gl, gclk, func() time.Duration { return time.Millisecond }, func() int { return 1 }) { + if k := gl.sched.seg(g.Sub(testT0).Nanoseconds()); k >= 0 { + ceiling[k]++ + } + } + + l, clk := newSim() + r := &RootModule{} + r.once.Do(func() {}) + r.limiter = l + calls := simulateGRPCOnlyRamp(t, segs, r.GRPCPacer(), clk) + + // The pre-fix pacer, which charged reflection like a call: the shortfall the run measured. + ol, oclk := newSim() + charged := simulateGRPCOnlyRamp(t, segs, func(ctx context.Context, _ string) error { return ol.Acquire(ctx) }, oclk) + + for k, sg := range segs { + budget := l.sched.integral(l.sched.bNs[k], l.sched.bNs[k+1]) + ratio := float64(calls[k]) / float64(ceiling[k]) + t.Logf("stage %d %d->%d: budget %.0f, limiter ceiling %d, gRPC calls %d (%.3f), with reflection charged %d (%.3f)", + k+1, sg.FromRps, sg.ToRps, budget, ceiling[k], calls[k], ratio, charged[k], float64(charged[k])/float64(ceiling[k])) + if ratio < 0.95 || calls[k] > ceiling[k] { + t.Errorf("stage %d: %d gRPC calls against a ceiling of %d (ratio %.3f), want within [0.95, 1]", k+1, calls[k], ceiling[k], ratio) + } + if sg.FromRps == sg.ToRps && float64(calls[k]) < 0.95*budget { + t.Errorf("hold stage %d: %d gRPC calls against a budget of %.0f", k+1, calls[k], budget) + } + } + // The control reproduces the run: holds at about 2/3 of the target. + if hold := float64(charged[3]) / 800; hold < 0.6 || hold > 0.72 { + t.Errorf("control: charging reflection delivered %.3f of the 80 rps hold, want about 2/3", hold) + } +} diff --git a/patches/k6-grpc-capture.patch b/patches/k6-grpc-capture.patch index 28fbce3..07350b5 100644 --- a/patches/k6-grpc-capture.patch +++ b/patches/k6-grpc-capture.patch @@ -29,7 +29,7 @@ index 7b7d904..88612b4 100644 + ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, + invoker grpc.UnaryInvoker, opts ...grpc.CallOption, + ) error { -+ if err := grpccapture.Pace(ctx); err != nil { ++ if err := grpccapture.Pace(ctx, method); err != nil { + return h.recordPaceFailure(ctx, method, err) + } + return invoker(ctx, method, req, reply, cc, opts...) @@ -41,7 +41,7 @@ index 7b7d904..88612b4 100644 + ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, + streamer grpc.Streamer, opts ...grpc.CallOption, + ) (grpc.ClientStream, error) { -+ if err := grpccapture.Pace(ctx); err != nil { ++ if err := grpccapture.Pace(ctx, method); err != nil { + return nil, h.recordPaceFailure(ctx, method, err) + } + return streamer(ctx, desc, cc, method, opts...) @@ -170,8 +170,8 @@ index 0000000..7215070 + +// Pacer blocks until a gRPC call may start, or returns an error when ctx ends first. It runs +// on the calling goroutine, once per unary call and once per stream open, before the call's -+// stats begin. -+type Pacer func(ctx context.Context) error ++// stats begin; method is the call's full method name ("/package.Service/Method"). ++type Pacer func(ctx context.Context, method string) error + +type pacerHolder struct{ p Pacer } + @@ -187,9 +187,9 @@ index 0000000..7215070 +} + +// Pace runs the registered Pacer; with none registered it returns nil at once. -+func Pace(ctx context.Context) error { ++func Pace(ctx context.Context, method string) error { + if h := pacer.Load(); h != nil { -+ return h.p(ctx) ++ return h.p(ctx, method) + } + return nil +} From 71f1ba383726c166fe843e1005e5fb621fe350d0 Mon Sep 17 00:00:00 2001 From: Dheeren Date: Wed, 2 Dec 2026 19:22:24 +0530 Subject: [PATCH 10/11] grpc: fail closed on a bad throughput section, redact credential metadata, test the patched build - The gRPC pacer returned nil when the throughput section failed to load or validate, and the pacer was not registered at all when the section could not be read. A gRPC-only script never calls the JS module's _enabled(), so a bad schedule ran its calls unpaced. Each call now fails with the section error; reflection stays free. - The capture file replaces credential-bearing metadata values (authorization, cookies, keys containing token/secret/password/api-key/session) with [REDACTED]. - The capture file must be a regular file; FIFOs, devices and directories are refused. - CI runs vet and the tests with -tags k6patched against the patched k6 that build.sh prepares, so the hooked code is tested, not only linked. --- .github/workflows/ci.yml | 8 +++++ README.md | 8 +++-- internal/grpccapture/capture.go | 49 ++++++++++++++++++++++++++-- internal/grpccapture/capture_test.go | 36 ++++++++++++++++++++ internal/throughput/grpc.go | 10 ++++-- internal/throughput/grpc_test.go | 14 ++++---- register.go | 7 ++-- 7 files changed, 114 insertions(+), 18 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 12ce6ad..6d7d682 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -59,3 +59,11 @@ jobs: run: GOOS=linux GOARCH=amd64 CGO_ENABLED=0 ./build.sh --output dist/k6 - name: Release gate run: bash scripts/release-gate.sh --binary dist/k6 --arch amd64 + # The hooked code (-tags k6patched) only compiles against the patched k6 that + # build.sh left at its fixed path; test it there too, so the pacer and capture + # hooks are exercised and not only linked. go.mod is edited in the runner only. + - name: go test (patched k6) + run: | + k6v="$(jq -r .k6Version extensions.json)" + go mod edit -replace "go.k6.io/k6/v2=/tmp/xk6-load-toolkit/k6-${k6v}-patched" + go test -race -count=1 -tags k6patched ./... diff --git a/README.md b/README.md index c7ceaf9..110ed4a 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,8 @@ variable does not scrub the process's initial environment block (on Linux, The JS module exports `_enabled()`, `_rate()`, `_acquire()`, `_acquireN(n)`, `_acquireUpTo(n)`, `_scheduled()` and `_dumpTrace()`. One limiter is shared by every VU in the process. `_enabled()` throws on an invalid section, so a -misconfigured run fails instead of running unthrottled. +misconfigured run fails instead of running unthrottled; gRPC calls, which are +paced without the JS module, each fail with the same error. `schedule` follows a piecewise-linear rate: for every t, grants in (t-1s, t] never exceed floor(W(t)), the integral of the rate over that second. @@ -112,7 +113,10 @@ whatever way the script imports `k6/net/grpc`. One sample is kept per (scenario, call name, status code). Messages are protojson, cut at 64 KB; each metadata map is cut at 16 KB. A file that cannot be opened or written turns capture off for the run, with one line on stderr. -Metadata is written as received: redact it before it leaves the machine. +Credential-bearing metadata values are replaced with `[REDACTED]`: +`authorization`, `proxy-authorization`, `cookie`, `set-cookie`, and any key +containing `token`, `secret`, `password`, `api-key`, `apikey` or `session`. +Other metadata is written as received. ### `sink` diff --git a/internal/grpccapture/capture.go b/internal/grpccapture/capture.go index 8d2769b..f02307c 100644 --- a/internal/grpccapture/capture.go +++ b/internal/grpccapture/capture.go @@ -95,10 +95,25 @@ func newRecorder(cfg config) *recorder { } } -// openCaptureFile opens the pre-created capture file for appending. It never creates the file -// and never follows a symlink: the caller creates the file, and only that file is trusted. +// openCaptureFile opens the pre-created capture file for appending. It never creates the file, +// never follows a symlink, and refuses anything but a regular file (a FIFO or device would +// block or swallow writes): the caller creates the file, and only that file is trusted. +// O_NONBLOCK keeps the open itself from blocking on a FIFO before the mode check runs. func openCaptureFile(path string) (io.Writer, error) { - return os.OpenFile(path, os.O_WRONLY|os.O_APPEND|syscall.O_NOFOLLOW, 0) //nolint:gosec // path supplied by the caller + f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0) //nolint:gosec // path supplied by the caller + if err != nil { + return nil, err + } + fi, err := f.Stat() + if err != nil { + _ = f.Close() + return nil, err + } + if !fi.Mode().IsRegular() { + _ = f.Close() + return nil, fmt.Errorf("grpccapture: %s is not a regular file", path) + } + return f, nil } // full reports whether both caps are reached; a full recorder ignores every later call. @@ -311,6 +326,31 @@ func rowName(tags map[string]string, fullMethod string) string { return fullMethod } +// redacted replaces the value of a credential-bearing metadata key in the capture file. +const redacted = "[REDACTED]" + +// sensitiveExact and sensitiveParts name metadata keys whose values are credentials. +// gRPC metadata keys are lowercase. +var ( + sensitiveExact = map[string]struct{}{ + "authorization": {}, "proxy-authorization": {}, "cookie": {}, "set-cookie": {}, + } + sensitiveParts = [...]string{"token", "secret", "password", "api-key", "apikey", "session"} +) + +func sensitiveKey(k string) bool { + k = strings.ToLower(k) + if _, ok := sensitiveExact[k]; ok { + return true + } + for _, p := range sensitiveParts { + if strings.Contains(k, p) { + return true + } + } + return false +} + // flattenMD renders metadata as name -> comma-joined values, capped at metadataLimit in total. // Keys are walked in sorted order so the same metadata always keeps the same entries at the cap. func flattenMD(md metadata.MD) map[string]string { @@ -323,6 +363,9 @@ func flattenMD(md metadata.MD) map[string]string { size := 0 for _, k := range keys { v := strings.Join(md[k], ", ") + if sensitiveKey(k) { + v = redacted + } size += len(k) + len(v) if size > metadataLimit { break diff --git a/internal/grpccapture/capture_test.go b/internal/grpccapture/capture_test.go index f7d1a75..27ea80c 100644 --- a/internal/grpccapture/capture_test.go +++ b/internal/grpccapture/capture_test.go @@ -11,6 +11,7 @@ import ( "regexp" "sort" "strings" + "syscall" "testing" "time" @@ -411,3 +412,38 @@ func TestFlattenMDKeepsTheSameEntriesEveryTime(t *testing.T) { t.Fatalf("the smallest key in sort order must be kept: %v", first) } } + +func TestFlattenMDRedactsCredentials(t *testing.T) { + md := metadata.MD{} + for _, k := range []string{"authorization", "cookie", "set-cookie", "proxy-authorization", + "x-api-key", "x-auth-token", "client-secret", "x-session-id", "db-password"} { + md.Set(k, "s3cr3t") + } + md.Set("content-type", "application/grpc") + md.Set("x-request-id", "abc") + out := flattenMD(md) + for k, v := range out { + if strings.Contains(v, "s3cr3t") { + t.Errorf("%s leaked its value", k) + } + } + if out["authorization"] != redacted || out["x-api-key"] != redacted { + t.Errorf("credentials not marked redacted: %v", out) + } + if out["content-type"] != "application/grpc" || out["x-request-id"] != "abc" { + t.Errorf("non-credential metadata changed: %v", out) + } +} + +func TestOpenCaptureFileRefusesNonRegularFiles(t *testing.T) { + if _, err := openCaptureFile(t.TempDir()); err == nil { + t.Fatal("opened a directory as the capture file") + } + fifo := filepath.Join(t.TempDir(), "fifo.jsonl") + if err := syscall.Mkfifo(fifo, 0o600); err != nil { + t.Skipf("mkfifo: %v", err) + } + if _, err := openCaptureFile(fifo); err == nil { + t.Fatal("opened a FIFO as the capture file") + } +} diff --git a/internal/throughput/grpc.go b/internal/throughput/grpc.go index e3e3326..d59b122 100644 --- a/internal/throughput/grpc.go +++ b/internal/throughput/grpc.go @@ -23,15 +23,19 @@ import ( // timeout is already running while it waits, which only matters when the backlog per process // exceeds the timeout. // -// No limiter (section absent) or a misconfigured one is a no-op here: the JS module's -// _enabled() throws on a bad configuration, which fails the run before any gRPC call is made. +// No limiter (section absent) is a no-op. A misconfigured section fails every call with the +// configuration error: a gRPC-only script never calls the JS module, so its _enabled() check +// cannot stop the run, and letting calls through would run them at no rate at all. func (r *RootModule) GRPCPacer() func(ctx context.Context, method string) error { return func(ctx context.Context, method string) error { if isReflectionMethod(method) { return nil } l, err := r.shared() - if err != nil || l == nil { + if err != nil { + return err + } + if l == nil { return nil } return l.Acquire(ctx) diff --git a/internal/throughput/grpc_test.go b/internal/throughput/grpc_test.go index abb5b10..c62072c 100644 --- a/internal/throughput/grpc_test.go +++ b/internal/throughput/grpc_test.go @@ -56,15 +56,15 @@ func TestGRPCPacerWithoutThroughputIsANoOp(t *testing.T) { } } -// A bad configuration fails the run through the JS module's _enabled(); the pacer must not -// turn it into a per-call gRPC error as well. -func TestGRPCPacerIgnoresAMisconfiguredSection(t *testing.T) { +// A gRPC-only script never calls the JS module, so a bad section must fail each gRPC call +// rather than let it through unpaced. Reflection stays free either way. +func TestGRPCPacerFailsClosedOnAMisconfiguredSection(t *testing.T) { r := rootWith(nil, errors.New("bad section")) - if _, err := r.shared(); err == nil { - t.Fatal("shared() hid the load error") + if err := r.GRPCPacer()(context.Background(), unaryMethod); err == nil || err.Error() != "bad section" { + t.Fatalf("pacer returned %v for a misconfigured section, want the section error", err) } - if err := r.GRPCPacer()(context.Background(), unaryMethod); err != nil { - t.Fatalf("pacer returned %v for a misconfigured section, want nil", err) + if err := r.GRPCPacer()(context.Background(), "/grpc.reflection.v1.ServerReflection/ServerReflectionInfo"); err != nil { + t.Fatalf("reflection returned %v, want nil", err) } } diff --git a/register.go b/register.go index ebed8ac..68142fd 100644 --- a/register.go +++ b/register.go @@ -33,12 +33,13 @@ func init() { registerGRPCHooks(thr) } -// registerGRPCHooks connects the gRPC capabilities to the k6 gRPC hooks: the pacer only when a -// throughput section is present (otherwise each gRPC call pays nothing but one atomic load), +// registerGRPCHooks connects the gRPC capabilities to the k6 gRPC hooks: the pacer when a +// throughput section is present or could not be read (a bad section must fail gRPC calls, not +// leave them unpaced; with no section each gRPC call pays nothing but one atomic load), // and the capture only when a grpcCapture section is present. Without the hooks (a build without -tags k6patched // build) both are no-ops. func registerGRPCHooks(thr *throughput.RootModule) { - if cfg, err := config.Throughput(); err == nil && cfg != nil { + if cfg, err := config.Throughput(); err != nil || cfg != nil { thr.RegisterGRPCPacer() } if cfg, err := config.GRPCCapture(); err == nil { From f25542a0aa735058a82bdc70856f91408b374551 Mon Sep 17 00:00:00 2001 From: Dheeren Date: Wed, 2 Dec 2026 20:09:06 +0530 Subject: [PATCH 11/11] grpc: stop a misconfigured run instead of failing each call, narrow pacer registration, widen redaction - A bad throughput section used to fail each gRPC call with status UNKNOWN. k6 returns a failed unary call to the script as a response, not an exception, so a gRPC-only script looped through failed calls at full speed and exited 0. Two changes make such a run fail: - Everything in the section that does not depend on the clock (podRps, the stages JSON and its bounds, durationSec/peakRps against the stages, peak >= 1, t0Ms being a number, schedule together with podRps) is now checked by throughput Config.Validate, so it is a configuration load error. The sink output already returns that error and k6 stops before any VU runs. - The patched interceptor now separates pacer errors. A context error (run stopping, deadline passing in the queue) still fails only that call and is recorded as before. Any other error aborts the test run through k6's test-run context, the mechanism execution.test.abort() uses: every VU stops and k6 exits with code 104 and the error. This covers a t0Ms outside the schedule window, found when the first call builds the limiter, and runs without the sink output. Reflection still takes no grant. The patch adds its own test, and CI runs it. - The pacer is registered only when the document has a throughput section, valid or not. The configuration package now reports whether the section is present, also for a document that failed to load, so a bad section elsewhere no longer fails gRPC calls when there is no throughput section. - Capture redaction also covers keys containing authorization, cookie, credential, signature, access-key/accesskey, private-key/privatekey and passwd, and keys with an "auth" segment (x-auth, but not :authority or author). A "-bin" suffix is ignored before matching. - The grpccapture package doc describes the redaction instead of saying metadata is written as received. - CI runs go vet -tags k6patched before the patched-build tests. --- .github/workflows/ci.yml | 6 ++ README.md | 28 +++-- SOURCE.md | 2 +- internal/config/config.go | 53 +++++++-- internal/config/config_test.go | 85 +++++++++++++-- internal/grpccapture/capture.go | 27 +++-- internal/grpccapture/capture_test.go | 31 ++++-- internal/grpccapture/config.go | 5 +- internal/throughput/config.go | 25 +++-- internal/throughput/grpc.go | 12 ++- internal/throughput/grpc_test.go | 49 ++++++++- internal/throughput/module.go | 76 +++++++------ internal/throughput/module_test.go | 34 ++++++ patches/k6-grpc-capture.patch | 155 +++++++++++++++++++++++++-- register.go | 13 +-- 15 files changed, 494 insertions(+), 107 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6d7d682..8aa3950 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,8 +62,14 @@ jobs: # The hooked code (-tags k6patched) only compiles against the patched k6 that # build.sh left at its fixed path; test it there too, so the pacer and capture # hooks are exercised and not only linked. go.mod is edited in the runner only. + - name: go test (k6 patch) + run: | + k6v="$(jq -r .k6Version extensions.json)" + cd "/tmp/xk6-load-toolkit/k6-${k6v}-patched" + go test -race -count=1 ./internal/lib/netext/grpcext/ - name: go test (patched k6) run: | k6v="$(jq -r .k6Version extensions.json)" go mod edit -replace "go.k6.io/k6/v2=/tmp/xk6-load-toolkit/k6-${k6v}-patched" + go vet -tags k6patched ./... go test -race -count=1 -tags k6patched ./... diff --git a/README.md b/README.md index 110ed4a..338423b 100644 --- a/README.md +++ b/README.md @@ -58,9 +58,15 @@ variable does not scrub the process's initial environment block (on Linux, The JS module exports `_enabled()`, `_rate()`, `_acquire()`, `_acquireN(n)`, `_acquireUpTo(n)`, `_scheduled()` and `_dumpTrace()`. One limiter is shared by -every VU in the process. `_enabled()` throws on an invalid section, so a -misconfigured run fails instead of running unthrottled; gRPC calls, which are -paced without the JS module, each fail with the same error. +every VU in the process. A section that is invalid whatever the time is (a bad +`podRps`, malformed or inconsistent `stages`, a `t0Ms` that is not a number) is +rejected when the configuration loads, like any invalid document: the +`load-toolkit-sink` output then refuses to start, so k6 stops before any VU +runs. Only a schedule whose `t0Ms` is outside its window, which depends on the +clock, is found later, when the first VU or gRPC call builds the limiter. Either +way, `_enabled()` throws, and the first paced gRPC call aborts the test run (k6 +exits with code 104 and the error), so a misconfigured run, with or without the +sink, never runs unthrottled or loops through failed calls. `schedule` follows a piecewise-linear rate: for every t, grants in (t-1s, t] never exceed floor(W(t)), the integral of the rate over that second. @@ -76,7 +82,8 @@ Setting `schedule` together with `podRps` is an error. `_acquireUpTo(n)` takes 1..n grants at one instant and returns how many, so a batch can be sent in slices that each fit the ceiling. -gRPC calls are paced too, with no script change: when the section is present, +gRPC calls are paced too, with no script change: when the section is present +(valid or not; with no `throughput` section gRPC calls are never paced or failed), the limiter is registered with the k6 gRPC hooks (see [k6 patches](#k6-patches)), and each unary call and each stream open takes one grant from the same limiter before it starts, so HTTP and gRPC share one rate. Messages inside a stream take @@ -113,10 +120,15 @@ whatever way the script imports `k6/net/grpc`. One sample is kept per (scenario, call name, status code). Messages are protojson, cut at 64 KB; each metadata map is cut at 16 KB. A file that cannot be opened or written turns capture off for the run, with one line on stderr. -Credential-bearing metadata values are replaced with `[REDACTED]`: -`authorization`, `proxy-authorization`, `cookie`, `set-cookie`, and any key -containing `token`, `secret`, `password`, `api-key`, `apikey` or `session`. -Other metadata is written as received. +Credential-bearing metadata values are replaced with `[REDACTED]`: any key +containing `authorization`, `cookie`, `token`, `secret`, `password`, `passwd`, +`credential`, `signature`, `api-key`, `apikey`, `access-key`, `accesskey`, +`private-key`, `privatekey` or `session`, and any key with an `auth` segment +(split on `-`, `_` and `.`, so `x-auth` matches but `:authority` and `author` +do not). A binary key's `-bin` suffix is ignored, so `authorization-bin` is +redacted too. Matching is case-insensitive. Other metadata is written as +received, so a service's own credential header under another name is not +redacted: treat the file as sensitive. ### `sink` diff --git a/SOURCE.md b/SOURCE.md index 5366098..26fe35d 100644 --- a/SOURCE.md +++ b/SOURCE.md @@ -47,7 +47,7 @@ these files. | Patch | What it changes | |---|---| | [`patches/k6-grpc-deadline.patch`](patches/k6-grpc-deadline.patch) | Pushes a finished gRPC call's `grpc_req_duration` sample against the VU context instead of the call's own, so calls that end with `DEADLINE_EXCEEDED` are recorded (stock k6 drops them, because the deadline cancels the call's context). | -| [`patches/k6-grpc-capture.patch`](patches/k6-grpc-capture.patch) | Adds the `lib/netext/grpccapture` package: a hook an extension can register to observe every gRPC call's stats (used by the `grpcCapture` capability) and a pacer called with the method name before each unary call and stream open (used by the throughput limiter). With nothing registered each call pays one atomic load. | +| [`patches/k6-grpc-capture.patch`](patches/k6-grpc-capture.patch) | Adds the `lib/netext/grpccapture` package: a hook an extension can register to observe every gRPC call's stats (used by the `grpcCapture` capability) and a pacer called with the method name before each unary call and stream open (used by the throughput limiter). A pacer error that is the call's context ending fails that call; any other pacer error aborts the test run through k6's test-run context (exit code 104). With nothing registered each call pays one atomic load. The patch carries its own test (`internal/lib/netext/grpcext/pace_test.go`). | ### Third-party extensions (15, pinned in `extensions.json`) diff --git a/internal/config/config.go b/internal/config/config.go index 9ef2afb..7b99a71 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -56,12 +56,13 @@ type EnvConfig struct { // The configuration is read once, in init(), because k6 copies the process // environment into the script's __ENV before any extension code runs again. var ( - loadedConfig *Config - configErr error + loadedConfig *Config + throughputPresent bool + configErr error ) func init() { - loadedConfig, configErr = loadFromEnv() + loadedConfig, throughputPresent, configErr = loadFromEnv() if errors.Is(configErr, errUnreadable) { // Nothing in the document could be read, so the variables it meant to hide // may still be set. Stop now, before k6 runs any script code. @@ -73,6 +74,11 @@ func init() { // Loaded returns the configuration read in init(), or the startup error. func Loaded() (*Config, error) { return loadedConfig, configErr } +// ThroughputPresent reports whether the document has a throughput section, whether or not it +// (or another section) failed to load. With no section, nothing that only the throughput +// capability does may fail because another section is bad. +func ThroughputPresent() bool { return throughputPresent } + // Throughput returns the throughput section read in init(), or the startup error. func Throughput() (*throughput.Config, error) { if configErr != nil { @@ -101,8 +107,8 @@ func TagFilter() (*tagfilter.Config, error) { // init() aborts the process on it. Its message is errStartup's. var errUnreadable = fmt.Errorf("%w", errStartup) -// loadFromEnv reads, validates and unsets the configuration. An absent -// variable means every capability is off. +// loadFromEnv reads, validates and unsets the configuration, and reports whether +// it has a throughput section. An absent variable means every capability is off. // // The keys in env.unset are removed before strict validation, by a lenient // pass that ignores every other field and anything after the document, so a @@ -111,29 +117,54 @@ var errUnreadable = fmt.Errorf("%w", errStartup) // any script code runs. The producer of the variable must emit valid JSON, // with env before the other sections so its keys are read even when a later // field is malformed. -func loadFromEnv() (*Config, error) { +func loadFromEnv() (cfg *Config, hasThroughput bool, err error) { raw, present := os.LookupEnv(ConfigEnv) diagnostics := os.Getenv(DiagnosticsEnv) _ = os.Unsetenv(ConfigEnv) _ = os.Unsetenv(DiagnosticsEnv) if !present { - return &Config{Version: SchemaVersion}, nil + return &Config{Version: SchemaVersion}, false, nil } if err := unsetListed(raw); err != nil { writeDiagnostics(diagnostics, fmt.Errorf("decode: %w", err)) - return nil, errUnreadable + return nil, false, errUnreadable } - cfg, err := Parse([]byte(raw)) + cfg, err = Parse([]byte(raw)) if cfg != nil && cfg.Env != nil { unsetAll(cfg.Env.Unset) // backstop: the list as the strict pass read it } if err != nil { writeDiagnostics(diagnostics, err) - return nil, errStartup + return nil, hasSection(raw, "throughput"), errStartup + } + return cfg, cfg.Throughput != nil, nil +} + +// hasSection reports whether the top-level object has a non-null value under name, matched +// the way the strict decode matches field names (case-insensitively, the last duplicate wins). +// It reads a document the strict decode rejected, so it skips every value without checking it. +func hasSection(raw, name string) bool { + dec := json.NewDecoder(strings.NewReader(raw)) + if tok, err := dec.Token(); err != nil || tok != json.Delim('{') { + return false + } + found := false + for dec.More() { + keyTok, err := dec.Token() + if err != nil { + return found + } + var value json.RawMessage + if err := dec.Decode(&value); err != nil { + return found + } + if key, _ := keyTok.(string); strings.EqualFold(key, name) { + found = !bytes.Equal(bytes.TrimSpace(value), []byte("null")) + } } - return cfg, nil + return found } // unsetListed walks the top-level object and unsets env.unset as soon as it is diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 885780f..e45c209 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -119,7 +119,7 @@ func TestParseConfig_Rejects(t *testing.T) { func TestLoadFromEnv_AbsentMeansEverythingOff(t *testing.T) { t.Setenv(ConfigEnv, "") os.Unsetenv(ConfigEnv) - cfg, err := loadFromEnv() + cfg, _, err := loadFromEnv() if err != nil || cfg.Sink != nil || cfg.Throughput != nil || cfg.TagFilter != nil { t.Fatalf("cfg=%+v err=%v", cfg, err) } @@ -130,7 +130,7 @@ func TestLoadFromEnv_UnsetsConfigAndListedKeys(t *testing.T) { t.Setenv("TOOLKIT_TEST_SECRET", "s") t.Setenv("TOOLKIT_TEST_KEEP", "k") t.Setenv(ConfigEnv, `{"version":1,"env":{"unset":["TOOLKIT_TEST_SECRET"]},"throughput":{"podRps":3}}`) - cfg, err := loadFromEnv() + cfg, _, err := loadFromEnv() if err != nil || cfg.Throughput == nil || cfg.Throughput.PodRPS != 3 { t.Fatalf("cfg=%+v err=%v", cfg, err) } @@ -152,7 +152,7 @@ func TestLoadFromEnv_InvalidConfig(t *testing.T) { t.Setenv("TOOLKIT_TEST_SECRET", "s") t.Setenv(ConfigEnv, `{"version":1,"env":{"unset":["TOOLKIT_TEST_SECRET"]},"sink":{"transport":{"endpoint":"http://x","table":"t"},"columns":[{"name":"c","from":"computed:nope"}]}}`) - cfg, err := loadFromEnv() + cfg, _, err := loadFromEnv() if cfg != nil || err != errStartup { t.Fatalf("cfg=%+v err=%v, want errStartup", cfg, err) } @@ -186,7 +186,7 @@ func TestLoadFromEnv_UnsetsListedKeysWhenStrictDecodeFails(t *testing.T) { t.Run(name, func(t *testing.T) { t.Setenv("TOOLKIT_TEST_SECRET", "s") t.Setenv(ConfigEnv, tc.raw) - cfg, err := loadFromEnv() + cfg, _, err := loadFromEnv() if cfg != nil || err != tc.wantErr { t.Fatalf("cfg=%v err=%v, want %v", cfg, err, tc.wantErr) } @@ -205,7 +205,7 @@ func TestLoadFromEnv_UnsetsListedKeysWhenStrictDecodeFails(t *testing.T) { func TestLoadFromEnv_UnreadableDocument(t *testing.T) { for _, raw := range []string{`{`, `not json`, `["env"]`, `{"env":{"unset":"K"}}`} { t.Setenv(ConfigEnv, raw) - if _, err := loadFromEnv(); err != errUnreadable { + if _, _, err := loadFromEnv(); err != errUnreadable { t.Fatalf("%q: err=%v, want errUnreadable", raw, err) } } @@ -246,7 +246,7 @@ func TestLoadFromEnv_CaseVariantsAndDuplicates(t *testing.T) { t.Run(name, func(t *testing.T) { t.Setenv("TOOLKIT_TEST_SECRET", "s") t.Setenv(ConfigEnv, tc.raw) - _, err := loadFromEnv() + _, _, err := loadFromEnv() if err != tc.wantErr { t.Fatalf("err=%v, want %v", err, tc.wantErr) } @@ -260,7 +260,7 @@ func TestLoadFromEnv_CaseVariantsAndDuplicates(t *testing.T) { // The schedule section is part of the strict configuration schema. func TestParseConfig_ScheduleSection(t *testing.T) { - cfg, err := Parse([]byte(`{"version":1,"throughput":{"schedule":{"stages":"[]","durationSec":"1","peakRps":"1","t0Ms":"1","warmupSec":2}}}`)) + cfg, err := Parse([]byte(`{"version":1,"throughput":{"schedule":{"stages":"[{\"fromRps\":1,\"toRps\":1,\"durationSec\":1}]","durationSec":"1","peakRps":"1","t0Ms":"1","warmupSec":2}}}`)) if err != nil || cfg.Throughput.Schedule == nil || cfg.Throughput.Schedule.WarmupSec != 2 { t.Fatalf("cfg=%+v err=%v", cfg, err) } @@ -272,6 +272,77 @@ func TestParseConfig_ScheduleSection(t *testing.T) { } } +// A schedule that is wrong whatever the time is rejected when the document is loaded, so the run +// fails at startup. Whether t0Ms is still inside the schedule depends on the clock and is left to +// the limiter: a t0Ms from 1970 loads. +func TestParseConfig_ValidatesScheduleAtLoad(t *testing.T) { + const stages = `[{\"fromRps\":0,\"toRps\":5,\"durationSec\":10}]` + doc := func(stages, duration, peak, t0, extra string) []byte { + return []byte(`{"version":1,"throughput":{` + extra + `"schedule":{"stages":"` + stages + + `","durationSec":"` + duration + `","peakRps":"` + peak + `","t0Ms":"` + t0 + `"}}}`) + } + if _, err := Parse(doc(stages, "10", "5", "1", "")); err != nil { + t.Fatalf("a schedule whose t0Ms has passed must load (the limiter checks the clock): %v", err) + } + cases := map[string]struct { + raw []byte + want string + }{ + "empty stages": {doc(`[]`, "10", "5", "1", ""), "1..30"}, + "malformed stages": {doc(`[{`, "10", "5", "1", ""), "JSON"}, + "duration mismatch": {doc(stages, "11", "5", "1", ""), "durationSec="}, + "peak mismatch": {doc(stages, "10", "4", "1", ""), "peakRps="}, + "all-zero schedule": {doc(`[{\"fromRps\":0,\"toRps\":0,\"durationSec\":10}]`, "10", "0", "1", ""), "peak"}, + "t0 not a number": {doc(stages, "10", "5", "soon", ""), "t0Ms"}, + "schedule and podRps": {doc(stages, "10", "5", "1", `"podRps":5,`), "podRps"}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + if _, err := Parse(tc.raw); err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("err = %v, want it to mention %q", err, tc.want) + } + }) + } +} + +// The pacer is registered only for a document with a throughput section, valid or not; a +// document whose only problem is another section must not register it. +func TestLoadFromEnv_ReportsTheThroughputSection(t *testing.T) { + const badSink = `"sink":{"transport":{"endpoint":"http://x","table":"t"},"columns":[{"name":"c","from":"computed:nope"}]}` + cases := map[string]struct { + raw string + want bool + wantErr error + }{ + "no section": {`{"version":1}`, false, nil}, + "valid section": {`{"version":1,"throughput":{"podRps":5}}`, true, nil}, + "null section": {`{"version":1,"throughput":null}`, false, nil}, + "invalid section": {`{"version":1,"throughput":{"podRps":0}}`, true, errStartup}, + "section of the wrong type": {`{"version":1,"throughput":{"podRps":"fast"}}`, true, errStartup}, + "unknown key in the section": {`{"version":1,"throughput":{"podRps":5,"burst":2}}`, true, errStartup}, + "case variant, other bad": {`{"version":1,"Throughput":{"podRps":5},"sinks":{}}`, true, errStartup}, + "valid section, other bad": {`{"version":1,"throughput":{"podRps":5},` + badSink + `}`, true, errStartup}, + "no section, other bad": {`{"version":1,` + badSink + `}`, false, errStartup}, + "no section, unknown top key": {`{"version":1,"sinks":{}}`, false, errStartup}, + "duplicate, last is null": {`{"version":1,"throughput":{"podRps":5},"throughput":null,"sinks":{}}`, false, errStartup}, + "duplicate, last is the section": {`{"version":1,"throughput":null,"throughput":{"podRps":0}}`, true, errStartup}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + t.Setenv(ConfigEnv, tc.raw) + _, got, err := loadFromEnv() + if got != tc.want || err != tc.wantErr { + t.Fatalf("throughput present = %v, err = %v; want %v, %v", got, err, tc.want, tc.wantErr) + } + }) + } + t.Setenv(ConfigEnv, "") + os.Unsetenv(ConfigEnv) + if _, got, err := loadFromEnv(); got || err != nil { + t.Fatalf("absent document: throughput present = %v, err = %v", got, err) + } +} + // fullSinkOptionsJSON sets every optional join, hold, bound and summary key. const fullSinkOptionsJSON = `{ "correlation": {"verdictMetric": "http_req_failed", "joinMetrics": ["op_result"]}, diff --git a/internal/grpccapture/capture.go b/internal/grpccapture/capture.go index f02307c..e875c1d 100644 --- a/internal/grpccapture/capture.go +++ b/internal/grpccapture/capture.go @@ -329,25 +329,34 @@ func rowName(tags map[string]string, fullMethod string) string { // redacted replaces the value of a credential-bearing metadata key in the capture file. const redacted = "[REDACTED]" -// sensitiveExact and sensitiveParts name metadata keys whose values are credentials. -// gRPC metadata keys are lowercase. +// sensitiveParts and sensitiveSegments name metadata keys whose values are credentials. A key +// matches when it contains a part anywhere, or has a segment (split on '-', '_' and '.') equal +// to a segment entry. "auth" is a segment, not a part, so x-auth and x-auth-token match while +// :authority and author do not. gRPC metadata keys are lowercase; a binary key's "-bin" suffix +// is ignored, so authorization-bin matches like authorization. var ( - sensitiveExact = map[string]struct{}{ - "authorization": {}, "proxy-authorization": {}, "cookie": {}, "set-cookie": {}, + sensitiveParts = [...]string{ + "authorization", "cookie", "token", "secret", "password", "passwd", "credential", + "signature", "api-key", "apikey", "access-key", "accesskey", "private-key", "privatekey", + "session", } - sensitiveParts = [...]string{"token", "secret", "password", "api-key", "apikey", "session"} + sensitiveSegments = [...]string{"auth"} ) func sensitiveKey(k string) bool { - k = strings.ToLower(k) - if _, ok := sensitiveExact[k]; ok { - return true - } + k = strings.TrimSuffix(strings.ToLower(k), "-bin") for _, p := range sensitiveParts { if strings.Contains(k, p) { return true } } + for _, seg := range strings.FieldsFunc(k, func(r rune) bool { return r == '-' || r == '_' || r == '.' }) { + for _, s := range sensitiveSegments { + if seg == s { + return true + } + } + } return false } diff --git a/internal/grpccapture/capture_test.go b/internal/grpccapture/capture_test.go index 27ea80c..e0d5049 100644 --- a/internal/grpccapture/capture_test.go +++ b/internal/grpccapture/capture_test.go @@ -415,23 +415,38 @@ func TestFlattenMDKeepsTheSameEntriesEveryTime(t *testing.T) { func TestFlattenMDRedactsCredentials(t *testing.T) { md := metadata.MD{} - for _, k := range []string{"authorization", "cookie", "set-cookie", "proxy-authorization", - "x-api-key", "x-auth-token", "client-secret", "x-session-id", "db-password"} { + secrets := []string{"authorization", "cookie", "set-cookie", "proxy-authorization", + "x-api-key", "x-auth-token", "client-secret", "x-session-id", "db-password", + "x-access-key", "access-key", "x-accesskey", "x-authorization", "x-auth", "auth", + "x-auth-user", "x_auth", "x-amz-credential", "client-credentials", "x-amz-signature", + "x-request-signature", "authorization-bin", "x-auth-bin", "token-bin", "x-private-key", + "X-Custom-Token"} + for _, k := range secrets { md.Set(k, "s3cr3t") } - md.Set("content-type", "application/grpc") - md.Set("x-request-id", "abc") + plain := map[string]string{ + "content-type": "application/grpc", "x-request-id": "abc", ":authority": "api.example.com", + "x-author": "jane", "author": "jane", "x-authority-zone": "eu", "x-trace-bin": "AQID", + "user-agent": "k6", "grpc-timeout": "5S", "x-tenant": "acme", + } + for k, v := range plain { + md.Set(k, v) + } out := flattenMD(md) for k, v := range out { if strings.Contains(v, "s3cr3t") { t.Errorf("%s leaked its value", k) } } - if out["authorization"] != redacted || out["x-api-key"] != redacted { - t.Errorf("credentials not marked redacted: %v", out) + for _, k := range secrets { + if k = strings.ToLower(k); out[k] != redacted { + t.Errorf("%s = %q, want %q", k, out[k], redacted) + } } - if out["content-type"] != "application/grpc" || out["x-request-id"] != "abc" { - t.Errorf("non-credential metadata changed: %v", out) + for k, v := range plain { + if out[k] != v { + t.Errorf("non-credential %s = %q, want %q unchanged", k, out[k], v) + } } } diff --git a/internal/grpccapture/config.go b/internal/grpccapture/config.go index 58263be..0a8a696 100644 --- a/internal/grpccapture/config.go +++ b/internal/grpccapture/config.go @@ -16,7 +16,10 @@ // // The file is opened for appending without O_CREATE and with O_NOFOLLOW, so the capability // never creates a file or follows a link; the caller pre-creates it. Nothing is written to -// stdout. Metadata is written as received: redact it before it leaves the machine. +// stdout. Metadata values under credential-bearing keys (see sensitiveKey in capture.go) are +// replaced with [REDACTED]; every other key is written as received. The list cannot know every +// service's custom header names, so treat the file as sensitive and review it before it leaves +// the machine. package grpccapture import ( diff --git a/internal/throughput/config.go b/internal/throughput/config.go index b672adb..16ab4f6 100644 --- a/internal/throughput/config.go +++ b/internal/throughput/config.go @@ -18,9 +18,10 @@ type Config struct { } // ScheduleConfig selects the time-varying limiter instead of podRps. Stages, -// DurationSec, PeakRps and T0Ms are carried as the producer received them and -// are checked when the limiter is built (module.go), so a bad value fails the -// run through the module rather than a guessed default. +// DurationSec, PeakRps and T0Ms are carried as the producer received them. +// Validate checks everything about them that does not depend on the clock, so a +// bad value fails the run at startup; whether t0Ms is still inside the schedule +// is checked when the limiter is built (module.go). type ScheduleConfig struct { // Stages is a JSON array of {fromRps, toRps, durationSec} segments. Stages string `json:"stages"` @@ -33,13 +34,21 @@ type ScheduleConfig struct { WarmupSec float64 `json:"warmupSec"` } -// Validate checks the section as part of the configuration document. +// Validate checks the section as part of the configuration document: everything +// except the clock-dependent t0Ms window, which only the limiter can check. func (t *Config) Validate() error { - if t.Schedule == nil && (math.IsNaN(t.PodRPS) || math.IsInf(t.PodRPS, 0) || t.PodRPS < 1) { - return fmt.Errorf("throughput.podRps: must be a number >= 1, got %v", t.PodRPS) - } if t.TraceCap < 0 { return errors.New("throughput.traceCap: must not be negative") } - return nil + if t.Schedule == nil { + if math.IsNaN(t.PodRPS) || math.IsInf(t.PodRPS, 0) || t.PodRPS < 1 { + return fmt.Errorf("throughput.podRps: must be a number >= 1, got %v", t.PodRPS) + } + return nil + } + if t.PodRPS != 0 { + return fmt.Errorf("throughput: schedule stages are set but podRps=%v is set too", t.PodRPS) + } + _, _, _, err := parseSchedule(t.Schedule) + return err } diff --git a/internal/throughput/grpc.go b/internal/throughput/grpc.go index d59b122..aecbdb5 100644 --- a/internal/throughput/grpc.go +++ b/internal/throughput/grpc.go @@ -23,9 +23,15 @@ import ( // timeout is already running while it waits, which only matters when the backlog per process // exceeds the timeout. // -// No limiter (section absent) is a no-op. A misconfigured section fails every call with the -// configuration error: a gRPC-only script never calls the JS module, so its _enabled() check -// cannot stop the run, and letting calls through would run them at no rate at all. +// No limiter (section absent) is a no-op. A section that cannot build a limiter returns its +// error, which is never a context error: a gRPC-only script never calls the JS module, so its +// _enabled() check cannot stop the run, and letting calls through would run them at no rate at +// all. The patched interceptor tells the two kinds apart. A context error fails only that call; +// any other error aborts the whole test run (k6 exits with code 104 and the error), because k6 +// hands a failed unary call back to the script as a response, not an exception, and a script +// that ignores the status would otherwise loop through failed calls and exit 0. Every +// clock-independent mistake in the section is already rejected at startup (Config.Validate); the +// one this reaches in practice is a t0Ms outside the schedule window when the first call is made. func (r *RootModule) GRPCPacer() func(ctx context.Context, method string) error { return func(ctx context.Context, method string) error { if isReflectionMethod(method) { diff --git a/internal/throughput/grpc_test.go b/internal/throughput/grpc_test.go index c62072c..3833ee0 100644 --- a/internal/throughput/grpc_test.go +++ b/internal/throughput/grpc_test.go @@ -3,6 +3,8 @@ package throughput import ( "context" "errors" + "strconv" + "strings" "testing" "time" ) @@ -56,18 +58,55 @@ func TestGRPCPacerWithoutThroughputIsANoOp(t *testing.T) { } } -// A gRPC-only script never calls the JS module, so a bad section must fail each gRPC call -// rather than let it through unpaced. Reflection stays free either way. +// isContextErr is the patched interceptor's test: a context error fails only that call, any +// other pacer error aborts the test run. +func isContextErr(err error) bool { + return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) +} + +// A gRPC-only script never calls the JS module, so a bad section must stop the run rather than +// let calls through unpaced: the pacer returns the section error, which is not a context error, +// so the interceptor aborts the test. Reflection stays free either way. func TestGRPCPacerFailsClosedOnAMisconfiguredSection(t *testing.T) { r := rootWith(nil, errors.New("bad section")) - if err := r.GRPCPacer()(context.Background(), unaryMethod); err == nil || err.Error() != "bad section" { + err := r.GRPCPacer()(context.Background(), unaryMethod) + if err == nil || err.Error() != "bad section" { t.Fatalf("pacer returned %v for a misconfigured section, want the section error", err) } + if isContextErr(err) { + t.Fatalf("a section error %v reads as a context error; the interceptor would not abort the run", err) + } if err := r.GRPCPacer()(context.Background(), "/grpc.reflection.v1.ServerReflection/ServerReflectionInfo"); err != nil { t.Fatalf("reflection returned %v, want nil", err) } } +// A schedule whose t0Ms is outside its window loads (only the clock makes it wrong), and the +// first paced call reports it as a non-context error, so the run is aborted at that call. +func TestGRPCPacerFailsClosedOnAStaleScheduleStart(t *testing.T) { + cfg := &Config{Schedule: &ScheduleConfig{ + Stages: `[{"fromRps":1,"toRps":1,"durationSec":60}]`, + DurationSec: "60", + PeakRps: "1", + T0Ms: strconv.FormatInt(time.Now().Add(-time.Hour).UnixMilli(), 10), + }} + if err := cfg.Validate(); err != nil { + t.Fatalf("Validate rejected a schedule that is only stale: %v", err) + } + r := rootWith(cfg, nil) + pace := r.GRPCPacer() + err := pace(context.Background(), unaryMethod) + if err == nil || !strings.Contains(err.Error(), "t0Ms") || isContextErr(err) { + t.Fatalf("pacer returned %v for a stale t0Ms, want the t0Ms error (not a context error)", err) + } + if again := pace(context.Background(), unaryMethod); again == nil || again.Error() != err.Error() { + t.Fatalf("second call returned %v, want the same error %v", again, err) + } + if err := pace(context.Background(), "/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo"); err != nil { + t.Fatalf("reflection returned %v, want nil", err) + } +} + // A call whose context ends while it waits (run stopping, or its deadline) must not hang and // must not consume a grant. func TestGRPCPacerStopsWaitingWhenTheCallEnds(t *testing.T) { @@ -84,8 +123,8 @@ func TestGRPCPacerStopsWaitingWhenTheCallEnds(t *testing.T) { go func() { done <- pace(ctx, unaryMethod) }() select { case err := <-done: - if err == nil { - t.Fatal("expected the wait to end with the context, got a grant") + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("wait ended with %v, want the context's DeadlineExceeded (only that call fails)", err) } case <-time.After(500 * time.Millisecond): t.Fatal("pacer did not return after the call's context ended") diff --git a/internal/throughput/module.go b/internal/throughput/module.go index 138cb7d..1bd8e96 100644 --- a/internal/throughput/module.go +++ b/internal/throughput/module.go @@ -95,8 +95,8 @@ func limiterFromConfig(cfg *Config) (limiter, error) { if cfg == nil { return nil, nil } - if cfg.Schedule != nil && cfg.PodRPS != 0 { - return nil, fmt.Errorf("throughput: schedule stages are set but podRps=%v is set too", cfg.PodRPS) + if err := cfg.Validate(); err != nil { + return nil, err } var ( l limiter @@ -134,64 +134,80 @@ func limiterFromConfig(cfg *Config) (limiter, error) { return l, nil } -// scheduleFromConfig parses and validates a schedule section. +// scheduleFromConfig builds the limiter for a schedule section: parseSchedule's checks, then +// the one that depends on the clock, that t0Ms is not more than maxT0Lead ahead and not past +// the schedule's end. That check runs when the limiter is built, at the first VU or the first +// gRPC call, so it can only fail the run from there. func scheduleFromConfig(sc *ScheduleConfig) (*ScheduleLimiter, error) { + segs, total, t0ms, err := parseSchedule(sc) + if err != nil { + return nil, err + } + t0 := time.UnixMilli(t0ms) + if since := time.Since(t0); since > time.Duration(total)*time.Second || since < -maxT0Lead { + return nil, fmt.Errorf("throughput: schedule t0Ms=%d is %v from now, outside the %ds schedule", t0ms, since, total) + } + l, err := NewScheduleLimiter(segs, t0) + if err != nil { + return nil, err + } + // Diagnostics only (stage log lines), so a non-positive value means no warm-up. + if sc.WarmupSec > 0 && !math.IsInf(sc.WarmupSec, 0) { + l.warmup = time.Duration(sc.WarmupSec * float64(time.Second)) + } + return l, nil +} + +// parseSchedule checks everything in a schedule section that does not depend on the clock and +// returns the segments, their total seconds and t0 in Unix ms. Config.Validate runs it when the +// configuration is loaded, so these errors fail the run at startup. +func parseSchedule(sc *ScheduleConfig) (segs []Segment, total int, t0ms int64, err error) { raw := sc.Stages if raw == "" { - return nil, errors.New("throughput: schedule requires stages") + return nil, 0, 0, errors.New("throughput: schedule requires stages") } if len(raw) > maxStagesBytes { - return nil, fmt.Errorf("throughput: schedule stages are %d bytes, max %d", len(raw), maxStagesBytes) + return nil, 0, 0, fmt.Errorf("throughput: schedule stages are %d bytes, max %d", len(raw), maxStagesBytes) } - var segs []Segment dec := json.NewDecoder(strings.NewReader(raw)) dec.DisallowUnknownFields() if err := dec.Decode(&segs); err != nil { - return nil, fmt.Errorf("throughput: schedule stages are not valid JSON segments: %v", err) + return nil, 0, 0, fmt.Errorf("throughput: schedule stages are not valid JSON segments: %v", err) } if len(segs) < 1 || len(segs) > maxSegments { - return nil, fmt.Errorf("throughput: schedule stages must have 1..%d segments, got %d", maxSegments, len(segs)) + return nil, 0, 0, fmt.Errorf("throughput: schedule stages must have 1..%d segments, got %d", maxSegments, len(segs)) } - total, peak := 0, 0 + peak := 0 for i, sg := range segs { if sg.FromRps < 0 || sg.ToRps < 0 { - return nil, fmt.Errorf("throughput: schedule segment %d: rps must be >= 0", i+1) + return nil, 0, 0, fmt.Errorf("throughput: schedule segment %d: rps must be >= 0", i+1) } if sg.DurationSec < 1 || sg.DurationSec > maxScheduleSec { - return nil, fmt.Errorf("throughput: schedule segment %d: durationSec must be 1..%d", i+1, maxScheduleSec) + return nil, 0, 0, fmt.Errorf("throughput: schedule segment %d: durationSec must be 1..%d", i+1, maxScheduleSec) } if i > 0 && sg.FromRps != segs[i-1].ToRps { - return nil, fmt.Errorf("throughput: schedule segment %d is not continuous with segment %d", i+1, i) + return nil, 0, 0, fmt.Errorf("throughput: schedule segment %d is not continuous with segment %d", i+1, i) } total += sg.DurationSec peak = max(peak, sg.FromRps, sg.ToRps) } if total > maxScheduleSec { - return nil, fmt.Errorf("throughput: schedule total %ds exceeds %ds", total, maxScheduleSec) + return nil, 0, 0, fmt.Errorf("throughput: schedule total %ds exceeds %ds", total, maxScheduleSec) + } + if peak < 1 { + return nil, 0, 0, fmt.Errorf("throughput: schedule peak must be >= 1, got %d", peak) } if want, err := strconv.Atoi(sc.DurationSec); err != nil || want != total { - return nil, fmt.Errorf("throughput: schedule durationSec=%q does not match the stages total %ds", sc.DurationSec, total) + return nil, 0, 0, fmt.Errorf("throughput: schedule durationSec=%q does not match the stages total %ds", sc.DurationSec, total) } if want, err := strconv.Atoi(sc.PeakRps); err != nil || want != peak { - return nil, fmt.Errorf("throughput: schedule peakRps=%q does not match the stages peak %d", sc.PeakRps, peak) - } - t0ms, err := strconv.ParseInt(sc.T0Ms, 10, 64) - if err != nil { - return nil, fmt.Errorf("throughput: schedule t0Ms=%q is not epoch milliseconds", sc.T0Ms) - } - t0 := time.UnixMilli(t0ms) - if since := time.Since(t0); since > time.Duration(total)*time.Second || since < -maxT0Lead { - return nil, fmt.Errorf("throughput: schedule t0Ms=%d is %v from now, outside the %ds schedule", t0ms, since, total) + return nil, 0, 0, fmt.Errorf("throughput: schedule peakRps=%q does not match the stages peak %d", sc.PeakRps, peak) } - l, err := NewScheduleLimiter(segs, t0) + t0ms, err = strconv.ParseInt(sc.T0Ms, 10, 64) if err != nil { - return nil, err - } - // Diagnostics only (stage log lines), so a non-positive value means no warm-up. - if sc.WarmupSec > 0 && !math.IsInf(sc.WarmupSec, 0) { - l.warmup = time.Duration(sc.WarmupSec * float64(time.Second)) + return nil, 0, 0, fmt.Errorf("throughput: schedule t0Ms=%q is not epoch milliseconds", sc.T0Ms) } - return l, nil + return segs, total, t0ms, nil } // traceHeader is "#t0 " for a schedule trace, so a replay can rebuild diff --git a/internal/throughput/module_test.go b/internal/throughput/module_test.go index 6455045..3c2fe78 100644 --- a/internal/throughput/module_test.go +++ b/internal/throughput/module_test.go @@ -110,6 +110,40 @@ func TestScheduleFromConfig(t *testing.T) { } } +// Config.Validate (run when the document loads) rejects every schedule mistake that does not +// depend on the clock, so those fail at startup; limiterFromConfig adds only the t0Ms window. +func TestValidateChecksTheScheduleExceptTheClock(t *testing.T) { + good := ScheduleConfig{ + Stages: `[{"fromRps":0,"toRps":50,"durationSec":60}]`, + PeakRps: "50", + DurationSec: "60", + T0Ms: strconv.FormatInt(time.Now().UnixMilli(), 10), + } + if err := (&Config{Schedule: &good}).Validate(); err != nil { + t.Fatalf("valid schedule: %v", err) + } + stale := good + stale.T0Ms = strconv.FormatInt(time.Now().Add(-time.Hour).UnixMilli(), 10) + if err := (&Config{Schedule: &stale}).Validate(); err != nil { + t.Fatalf("Validate must not read the clock: %v", err) + } + if _, err := limiterFromConfig(&Config{Schedule: &stale}); err == nil || !strings.Contains(err.Error(), "t0Ms") { + t.Fatalf("limiterFromConfig on a stale t0Ms: %v, want the t0Ms error", err) + } + for name, edit := range map[string]func(*ScheduleConfig){ + "stages": func(c *ScheduleConfig) { c.Stages = `[]` }, + "duration": func(c *ScheduleConfig) { c.DurationSec = "61" }, + "peak": func(c *ScheduleConfig) { c.PeakRps = "49" }, + "t0Ms": func(c *ScheduleConfig) { c.T0Ms = "later" }, + } { + bad := good + edit(&bad) + if err := (&Config{Schedule: &bad}).Validate(); err == nil { + t.Errorf("bad %s: Validate accepted it", name) + } + } +} + // The warm-up only shifts the stage log; a non-positive value means none. func TestScheduleWarmup(t *testing.T) { base := ScheduleConfig{ diff --git a/patches/k6-grpc-capture.patch b/patches/k6-grpc-capture.patch index 07350b5..8926da1 100644 --- a/patches/k6-grpc-capture.patch +++ b/patches/k6-grpc-capture.patch @@ -1,16 +1,28 @@ diff --git a/internal/lib/netext/grpcext/conn.go b/internal/lib/netext/grpcext/conn.go -index 7b7d904..88612b4 100644 +index 7b7d904..1ff4f6a 100644 --- a/internal/lib/netext/grpcext/conn.go +++ b/internal/lib/netext/grpcext/conn.go -@@ -13,6 +13,7 @@ import ( +@@ -4,6 +4,7 @@ package grpcext + import ( + "context" + "encoding/json" ++ "errors" + "fmt" + "net" + "strconv" +@@ -12,7 +13,11 @@ import ( + "github.com/sirupsen/logrus" ++ "go.k6.io/k6/v2/errext" ++ "go.k6.io/k6/v2/errext/exitcodes" ++ "go.k6.io/k6/v2/internal/execution" "go.k6.io/k6/v2/lib" + "go.k6.io/k6/v2/lib/netext/grpccapture" "go.k6.io/k6/v2/metrics" protov1 "github.com/golang/protobuf/proto" //nolint:staticcheck,nolintlint // this is the old v1 version -@@ -91,9 +92,56 @@ func DefaultOptions(getState func() *lib.State, getVUCtx func() context.Context) +@@ -91,9 +96,80 @@ func DefaultOptions(getState func() *lib.State, getVUCtx func() context.Context) grpc.WithReturnConnectionError(), //nolint:staticcheck grpc.WithStatsHandler(statsHandler{getState: getState, getVUCtx: getVUCtx}), grpc.WithContextDialer(dialer), @@ -23,14 +35,15 @@ index 7b7d904..88612b4 100644 +// paceUnary and paceStream wait on the registered grpccapture pacer before the call starts. +// They are interceptors, not TagRPC, because grpc-go stamps the call's BeginTime before +// TagRPC: a wait there would be counted in grpc_req_duration. A wait cut short by the call's -+// context fails the call before anything is sent, and is recorded as a failed call. ++// context fails the call before anything is sent, and is recorded as a failed call. Any other ++// pacer error aborts the test run (see paceFailure). +func paceUnary(h statsHandler) grpc.UnaryClientInterceptor { + return func( + ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, + invoker grpc.UnaryInvoker, opts ...grpc.CallOption, + ) error { + if err := grpccapture.Pace(ctx, method); err != nil { -+ return h.recordPaceFailure(ctx, method, err) ++ return h.paceFailure(ctx, method, err) + } + return invoker(ctx, method, req, reply, cc, opts...) + } @@ -42,12 +55,35 @@ index 7b7d904..88612b4 100644 + streamer grpc.Streamer, opts ...grpc.CallOption, + ) (grpc.ClientStream, error) { + if err := grpccapture.Pace(ctx, method); err != nil { -+ return nil, h.recordPaceFailure(ctx, method, err) ++ return nil, h.paceFailure(ctx, method, err) + } + return streamer(ctx, desc, cc, method, opts...) + } +} + ++// paceFailure turns a pacer error into the call's error. A context error (the run stopping, or ++// the call's deadline passing in the queue) is that call's own failure and is recorded as one. ++// Any other error means the pacer cannot pace at all, and it would fail every later call the ++// same way. k6 returns a failed unary call to the script as a response rather than an ++// exception, so a script that ignores the status would loop through failed calls at full ++// speed and exit 0. The run is aborted instead, through the same test-run context ++// execution.test.abort() cancels: k6 stops every VU and exits with code 104 (invalid ++// configuration) and this error. The call itself fails with FAILED_PRECONDITION and is not ++// recorded, as it never started. ++func (h statsHandler) paceFailure(ctx context.Context, method string, err error) error { ++ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { ++ return h.recordPaceFailure(ctx, method, err) ++ } ++ abortErr := errext.WithAbortReasonIfNone( ++ errext.WithExitCodeIfNone(fmt.Errorf("test aborted: gRPC calls cannot be paced: %w", err), exitcodes.InvalidConfig), ++ errext.AbortedByScriptError, ++ ) ++ if !execution.AbortTestRun(ctx, abortErr) && h.getVUCtx != nil { ++ execution.AbortTestRun(h.getVUCtx(), abortErr) ++ } ++ return status.Error(codes.FailedPrecondition, abortErr.Error()) ++} ++ +// recordPaceFailure reports a call whose context ended while the pacer held it as the failed +// call it is: the stats handler gets the TagRPC and End a started call gets, so one +// grpc_req_duration sample is pushed with the context's status (DEADLINE_EXCEEDED or CANCELLED) @@ -67,7 +103,7 @@ index 7b7d904..88612b4 100644 // Dial establish a gRPC connection. func Dial(ctx context.Context, addr string, types *protoregistry.Types, options ...grpc.DialOption) (*Conn, error) { conn, err := grpc.DialContext(ctx, addr, options...) //nolint:staticcheck -@@ -255,8 +303,13 @@ func (statsHandler) HandleConn(context.Context, grpcstats.ConnStats) { +@@ -255,8 +331,13 @@ func (statsHandler) HandleConn(context.Context, grpcstats.ConnStats) { } // TagRPC implements the grpcstats.Handler interface @@ -83,7 +119,7 @@ index 7b7d904..88612b4 100644 return ctx } -@@ -303,6 +356,20 @@ func (h statsHandler) HandleRPC(ctx context.Context, stat grpcstats.RPCStats) { +@@ -303,6 +384,20 @@ func (h statsHandler) HandleRPC(ctx context.Context, stat grpcstats.RPCStats) { }) } @@ -104,12 +140,108 @@ index 7b7d904..88612b4 100644 // (rogchap) Re-using --http-debug flag as gRPC is technically still HTTP if state.Options.HTTPDebug.String != "" { logger := state.Logger.WithField("source", "http-debug") +diff --git a/internal/lib/netext/grpcext/pace_test.go b/internal/lib/netext/grpcext/pace_test.go +new file mode 100644 +index 0000000..3a1e87e +--- /dev/null ++++ b/internal/lib/netext/grpcext/pace_test.go +@@ -0,0 +1,90 @@ ++package grpcext ++ ++import ( ++ "context" ++ "errors" ++ "io" ++ "testing" ++ ++ "github.com/sirupsen/logrus" ++ "github.com/stretchr/testify/assert" ++ "github.com/stretchr/testify/require" ++ "google.golang.org/grpc" ++ "google.golang.org/grpc/codes" ++ "google.golang.org/grpc/status" ++ ++ "go.k6.io/k6/v2/errext" ++ "go.k6.io/k6/v2/errext/exitcodes" ++ "go.k6.io/k6/v2/internal/execution" ++ "go.k6.io/k6/v2/lib" ++ "go.k6.io/k6/v2/lib/netext/grpccapture" ++) ++ ++func paceTestRun(t *testing.T, pacer grpccapture.Pacer) (context.Context, statsHandler) { ++ t.Helper() ++ grpccapture.RegisterPacer(pacer) ++ t.Cleanup(func() { grpccapture.RegisterPacer(nil) }) ++ logger := logrus.New() ++ logger.SetOutput(io.Discard) ++ runCtx, _ := execution.NewTestRunContext(context.Background(), logger) ++ return runCtx, statsHandler{getState: func() *lib.State { return nil }} ++} ++ ++func assertAbortedAsInvalidConfig(t *testing.T, runCtx context.Context, callErr error) { ++ t.Helper() ++ assert.Equal(t, codes.FailedPrecondition, status.Code(callErr)) ++ assert.Contains(t, callErr.Error(), "bad section") ++ select { ++ case <-runCtx.Done(): ++ default: ++ t.Fatal("the test run was not aborted") ++ } ++ reason := execution.GetCancelReasonIfTestAborted(runCtx) ++ require.Error(t, reason) ++ assert.Contains(t, reason.Error(), "bad section") ++ var withCode errext.HasExitCode ++ require.True(t, errors.As(reason, &withCode)) ++ assert.Equal(t, exitcodes.InvalidConfig, withCode.ExitCode()) ++} ++ ++// A pacer that cannot pace aborts the run: the unary call fails without being sent. The tests ++// share the process-wide pacer, so none runs in parallel. ++func TestPaceUnaryAbortsTheRunOnAPacerError(t *testing.T) { ++ runCtx, h := paceTestRun(t, func(context.Context, string) error { return errors.New("bad section") }) ++ invoked := false ++ err := paceUnary(h)(runCtx, "/sut.v1.LoadSut/Unary", nil, nil, nil, ++ func(context.Context, string, any, any, *grpc.ClientConn, ...grpc.CallOption) error { ++ invoked = true ++ return nil ++ }) ++ assert.False(t, invoked, "the call was sent") ++ assertAbortedAsInvalidConfig(t, runCtx, err) ++} ++ ++func TestPaceStreamAbortsTheRunOnAPacerError(t *testing.T) { ++ runCtx, h := paceTestRun(t, func(context.Context, string) error { return errors.New("bad section") }) ++ opened := false ++ cs, err := paceStream(h)(runCtx, &grpc.StreamDesc{}, nil, "/sut.v1.LoadSut/Stream", ++ func(context.Context, *grpc.StreamDesc, *grpc.ClientConn, string, ...grpc.CallOption) (grpc.ClientStream, error) { ++ opened = true ++ return nil, nil ++ }) ++ assert.Nil(t, cs) ++ assert.False(t, opened, "the stream was opened") ++ assertAbortedAsInvalidConfig(t, runCtx, err) ++} ++ ++// A wait cut short by the call's own context fails that call only. ++func TestPaceUnaryContextErrorFailsOnlyTheCall(t *testing.T) { ++ runCtx, h := paceTestRun(t, func(ctx context.Context, _ string) error { return ctx.Err() }) ++ callCtx, cancel := context.WithCancel(runCtx) ++ cancel() ++ err := paceUnary(h)(callCtx, "/sut.v1.LoadSut/Unary", nil, nil, nil, ++ func(context.Context, string, any, any, *grpc.ClientConn, ...grpc.CallOption) error { ++ t.Fatal("the call was sent") ++ return nil ++ }) ++ assert.Equal(t, codes.Canceled, status.Code(err)) ++ assert.NoError(t, runCtx.Err(), "a cancelled call aborted the run") ++ assert.NoError(t, execution.GetCancelReasonIfTestAborted(runCtx)) ++} diff --git a/lib/netext/grpccapture/grpccapture.go b/lib/netext/grpccapture/grpccapture.go new file mode 100644 -index 0000000..7215070 +index 0000000..b906a53 --- /dev/null +++ b/lib/netext/grpccapture/grpccapture.go -@@ -0,0 +1,83 @@ +@@ -0,0 +1,86 @@ +// Package grpccapture lets an xk6 extension observe the client-side stats of every gRPC call a +// VU makes. It is the hook github.com/browserstack/xk6-load-toolkit uses to capture gRPC +// request/response samples; it is added by that repository's patch, not by upstream k6. @@ -171,6 +303,9 @@ index 0000000..7215070 +// Pacer blocks until a gRPC call may start, or returns an error when ctx ends first. It runs +// on the calling goroutine, once per unary call and once per stream open, before the call's +// stats begin; method is the call's full method name ("/package.Service/Method"). ++// ++// An error wrapping context.Canceled or context.DeadlineExceeded fails that call only. Any ++// other error means the pacer cannot pace: k6 aborts the test run with it (exit code 104). +type Pacer func(ctx context.Context, method string) error + +type pacerHolder struct{ p Pacer } diff --git a/register.go b/register.go index 68142fd..f586aef 100644 --- a/register.go +++ b/register.go @@ -33,13 +33,14 @@ func init() { registerGRPCHooks(thr) } -// registerGRPCHooks connects the gRPC capabilities to the k6 gRPC hooks: the pacer when a -// throughput section is present or could not be read (a bad section must fail gRPC calls, not -// leave them unpaced; with no section each gRPC call pays nothing but one atomic load), -// and the capture only when a grpcCapture section is present. Without the hooks (a build without -tags k6patched -// build) both are no-ops. +// registerGRPCHooks connects the gRPC capabilities to the k6 gRPC hooks: the pacer when the +// document has a throughput section, valid or not (a bad section must stop the run, not leave +// gRPC calls unpaced), and the capture only when a grpcCapture section is present. With no +// throughput section the pacer is not registered, so a bad section elsewhere never fails a gRPC +// call (the sink output fails the run at startup for that) and each call pays one atomic load. +// Without the hooks (a build without -tags k6patched) both are no-ops. func registerGRPCHooks(thr *throughput.RootModule) { - if cfg, err := config.Throughput(); err != nil || cfg != nil { + if config.ThroughputPresent() { thr.RegisterGRPCPacer() } if cfg, err := config.GRPCCapture(); err == nil {