Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

8.6 KB
Raw Blame
package recorder

import (
	"encoding/json"
	"math"
	"os"
	"sort"
	"strings"
	"sync"
	"time"

	"go.k6.io/k6/metrics"
)

// Live telemetry contains counters and one bounded latency window, never responses.
type flowProgress struct {
	ServerP99       *float64  `json:"server_p99_ms"`
	ServerSamples   []float64 `json:"server_samples_ms,omitempty"`
	serverLatencies []float64
	Successes       uint64   `json:"successes"`
	Failures        uint64   `json:"failures"`
	TPS             float64  `json:"tps"`
	P90             *float64 `json:"p90_ms"`
	P99             *float64 `json:"p99_ms"`
	windowSuccess   uint64
	latencies       []float64
}
type connectorProgress struct {
	Assigned  uint64 `json:"assigned"`
	Confirmed uint64 `json:"confirmed"`
	Successes uint64 `json:"successes"`
}
type liveProgress struct {
	ServerP99           *float64                      `json:"server_p99_ms"`
	ServerSamples       []float64                     `json:"server_samples_ms,omitempty"`
	P99                 *float64                      `json:"p99_ms"`
	Elapsed             float64                       `json:"elapsed_seconds"`
	Iterations          uint64                        `json:"iterations"`
	Dropped             uint64                        `json:"dropped"`
	HTTPAttempts        uint64                        `json:"http_attempts"`
	HTTPErrors          uint64                        `json:"http_errors"`
	ConfirmHTTPAttempts uint64                        `json:"confirm_http_attempts"`
	ConfirmHTTPErrors   uint64                        `json:"confirm_http_errors"`
	SuccessfulTPS       float64                       `json:"successful_tps"`
	Recorder            Stats                         `json:"recorder"`
	Connectors          map[string]*connectorProgress `json:"connectors,omitempty"`
	Flows               map[string]*flowProgress      `json:"flows"`
	Control             *controlSnapshot              `json:"control,omitempty"`
}
type progressCollector struct {
	mu                sync.Mutex
	started, previous time.Time
	state             liveProgress
	latencies         []float64
	serverLatencies   []float64
}

// newProgressCollector initializes run counters and per-flow buckets from
// scenario metadata. Unknown flow names are not added during sample collection.
func newProgressCollector(metadata map[string]interface{}) *progressCollector {
	p := &progressCollector{started: time.Now(), previous: time.Now()}
	p.state.Flows = map[string]*flowProgress{}
	p.state.Connectors = map[string]*connectorProgress{}
	if scenarios, ok := metadata["scenarios"].([]interface{}); ok {
		for _, raw := range scenarios {
			if f, ok := raw.(map[string]interface{}); ok {
				if name, ok := f["name"].(string); ok {
					p.state.Flows[name] = &flowProgress{}
				}
			}
		}
	}
	return p
}

// add aggregates k6 counters and payment-confirm latency samples under p.mu.
// Latency buffers retain at most 8,192 samples per window; only configured flow
// names contribute per-flow totals, preventing phase metrics from double counting.
func (p *progressCollector) add(containers []metrics.SampleContainer) {
	p.mu.Lock()
	defer p.mu.Unlock()
	for _, container := range containers {
		for _, sample := range container.GetSamples() {
			name := sample.Metric.Name
			switch name {
			case "connector_assigned", "connector_confirmed", "connector_succeeded":
				if sample.Tags != nil {
					if connector, ok := sample.Tags.Get("connector"); ok && connector != "" {
						c := p.state.Connectors[connector]
						if c == nil {
							c = &connectorProgress{}
							p.state.Connectors[connector] = c
						}
						switch name {
						case "connector_assigned":
							c.Assigned += uint64(sample.Value)
						case "connector_confirmed":
							c.Confirmed += uint64(sample.Value)
						case "connector_succeeded":
							c.Successes += uint64(sample.Value)
						}
					}
				}
			case "payment_confirm_server_latency_ms":
				if sample.Value >= 0 && !math.IsNaN(sample.Value) && !math.IsInf(sample.Value, 0) && len(p.serverLatencies) < 8192 {
					p.serverLatencies = append(p.serverLatencies, sample.Value)
				}
			case "payment_confirm_latency_ms":
				if len(p.latencies) < 8192 {
					p.latencies = append(p.latencies, sample.Value)
				}
			case "iterations":
				p.state.Iterations += uint64(sample.Value)
			case "dropped_iterations":
				p.state.Dropped += uint64(sample.Value)
			case "http_reqs":
				p.state.HTTPAttempts += uint64(sample.Value)
				if sample.Tags != nil {
					if operation, ok := sample.Tags.Get("operation"); ok && operation == "payment_confirm" {
						p.state.ConfirmHTTPAttempts += uint64(sample.Value)
					}
				}
			case "http_req_failed":
				if sample.Value > 0 {
					p.state.HTTPErrors++
					if sample.Tags != nil {
						if operation, ok := sample.Tags.Get("operation"); ok && operation == "payment_confirm" {
							p.state.ConfirmHTTPErrors++
						}
					}
				}
			default:
				if strings.HasPrefix(name, "scenario_success_") {
					if f := p.state.Flows[strings.TrimPrefix(name, "scenario_success_")]; f != nil {
						f.Successes += uint64(sample.Value)
						f.windowSuccess += uint64(sample.Value)
					}
				}
				if strings.HasPrefix(name, "scenario_failure_") {
					if f := p.state.Flows[strings.TrimPrefix(name, "scenario_failure_")]; f != nil {
						f.Failures += uint64(sample.Value)
					}
				}
				if strings.HasPrefix(name, "payment_confirm_server_ms_") {
					if f := p.state.Flows[strings.TrimPrefix(name, "payment_confirm_server_ms_")]; f != nil && sample.Value >= 0 && !math.IsNaN(sample.Value) && !math.IsInf(sample.Value, 0) && len(f.serverLatencies) < 8192 {
						f.serverLatencies = append(f.serverLatencies, sample.Value)
					}
				}
				if strings.HasPrefix(name, "payment_confirm_ms_") {
					if f := p.state.Flows[strings.TrimPrefix(name, "payment_confirm_ms_")]; f != nil && len(f.latencies) < 8192 {
						f.latencies = append(f.latencies, sample.Value)
					}
				}
			}
		}
	}
}

// bytes serializes live progress with the supplied recorder counters.
// Cumulative counts are retained, while TPS deltas and latency buffers reset
// after each publication; empty windows emit unavailable latency rather than zero.
func (p *progressCollector) bytes(stats Stats) []byte {
	p.mu.Lock()
	defer p.mu.Unlock()
	now := time.Now()
	seconds := now.Sub(p.previous).Seconds()
	p.previous = now
	p.state.Elapsed = now.Sub(p.started).Seconds()
	p.state.Recorder = stats
	p.state.SuccessfulTPS = 0
	p.state.ServerP99 = serverPercentile(p.serverLatencies)
	p.state.ServerSamples = p.serverLatencies
	p.serverLatencies = p.serverLatencies[:0]
	p.state.P99 = nil
	if len(p.latencies) > 0 {
		sort.Float64s(p.latencies)
		value := p.latencies[int(float64(len(p.latencies)-1)*0.99)]
		p.state.P99 = &value
		p.latencies = p.latencies[:0]
	}
	for _, f := range p.state.Flows {
		f.TPS = float64(f.windowSuccess) / seconds
		f.windowSuccess = 0
		p.state.SuccessfulTPS += f.TPS
		f.ServerP99 = serverPercentile(f.serverLatencies)
		f.ServerSamples = f.serverLatencies
		f.serverLatencies = f.serverLatencies[:0]
		f.P90 = nil
		f.P99 = nil
		if len(f.latencies) > 0 {
			sort.Float64s(f.latencies)
			value := f.latencies[int(float64(len(f.latencies)-1)*0.9)]
			f.P90 = &value
			p99 := f.latencies[int(float64(len(f.latencies)-1)*0.99)]
			f.P99 = &p99
			f.latencies = f.latencies[:0]
		}
	}
	raw, _ := json.Marshal(p.state)
	return raw
}

// writeProgress combines live metrics with recorder and optional controller
// state, then atomically replaces the progress file. Controller counters override
// k6 scheduling totals; write failures fail the recorder rather than leaving
// telemetry loss unreported.
func (o *sqliteOutput) writeProgress() {
	if o.progressFile == "" {
		return
	}
	raw := o.progress.bytes(o.writer.Snapshot())
	if o.control != nil {
		var state liveProgress
		_ = json.Unmarshal(raw, &state)
		snapshot := o.control.snapshot()
		state.Control = &snapshot
		state.Elapsed = snapshot.Wall
		state.Dropped = snapshot.Dropped
		state.Iterations = 0
		for _, flow := range state.Flows {
			state.Iterations += flow.Successes + flow.Failures
		}
		raw, _ = json.Marshal(state)
	}
	if err := os.WriteFile(o.progressFile+".tmp", raw, 0600); err != nil {
		o.writer.fail(err)
		return
	}
	if err := os.Rename(o.progressFile+".tmp", o.progressFile); err != nil {
		o.writer.fail(err)
	}
}

// serverPercentile sorts the supplied window in place and returns its p99
// using the lower indexed sample at floor((n-1)*0.99). Empty windows return nil;
// this live estimate is not a percentile over the entire recorded run.
func serverPercentile(values []float64) *float64 {
	if len(values) == 0 {
		return nil
	}
	sort.Float64s(values)
	value := values[int(float64(len(values)-1)*.99)]
	return &value
}