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

9.1 KB
Raw Blame
package recorder

import (
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"sync"
	"time"

	"go.k6.io/k6/errext"
	"go.k6.io/k6/js/modules"
	"go.k6.io/k6/metrics"
	"go.k6.io/k6/output"
)

var active struct {
	sync.RWMutex
	writer  *Writer
	last    *Stats
	control *loadControl
}

// init registers the JavaScript module and output extension under the names
// used by scenarios and the k6 --out flag.
func init() {
	modules.Register("k6/x/sqlite-recorder", &module{})
	output.RegisterExtension("sqlite-recorder", newOutput)
}

type module struct{}
type instance struct{ vu modules.VU }

// NewModuleInstance binds the module to a virtual user so admission waits
// can observe that VU's cancellation context.
func (*module) NewModuleInstance(vu modules.VU) modules.Instance { return &instance{vu: vu} }

// Exports exposes recording, admission control, and statistics to scenarios.
// The attribution version lets scripts detect connector-aware recorder support.
func (i *instance) Exports() modules.Exports {
	return modules.Exports{Default: map[string]interface{}{"connectorAttribution": 1, "record": record, "begin": begin, "finish": finish, "complete": complete, "stats": snapshot, "enter": i.enter, "leave": leave}}
}

// enter waits for admission through the active load controller. It returns
// false when control is unavailable or the VU is cancelled before admission.
func (i *instance) enter(name string) bool {
	active.RLock()
	c := active.control
	active.RUnlock()
	return c != nil && c.enter(i.vu.Context(), name)
}

// leave releases one admitted flow when a controller exists, allowing pause
// and completion to finish draining in-flight work.
func leave() {
	active.RLock()
	c := active.control
	active.RUnlock()
	if c != nil {
		c.leave()
	}
}

// current reads the active writer under the shared lock and rejects recording
// when k6 has not started the sqlite-recorder output.
func current() (*Writer, error) {
	active.RLock()
	defer active.RUnlock()
	if active.writer == nil {
		return nil, errors.New("SQLite recorder not started; use --out sqlite-recorder")
	}
	return active.writer, nil
}

// record queues an already assembled response projection on the active writer.
// Writer availability, capacity, and persistence failures propagate to the caller.
func record(r Record) error {
	w, err := current()
	if err != nil {
		return err
	}
	return w.Enqueue(r)
}

// snapshot returns current recorder counters, or the final retained counters
// after shutdown. It fails when no run has produced statistics.
func snapshot() (Stats, error) {
	active.RLock()
	defer active.RUnlock()
	if active.writer != nil {
		return active.writer.Snapshot(), nil
	}
	if active.last != nil {
		return *active.last, nil
	}
	return Stats{}, errors.New("SQLite recorder has no run")
}

type sqliteOutput struct {
	params       output.Params
	writer       *Writer
	stop         func(error)
	monitorStop  chan struct{}
	monitorDone  chan struct{}
	progressFile string
	progress     *progressCollector
	control      *loadControl
}

// newOutput constructs the k6 output without opening resources; Start performs
// environment validation and initializes recording.
func newOutput(params output.Params) (output.Output, error) {
	return &sqliteOutput{params: params}, nil
}

// Description supplies the human-readable output name shown by k6.
func (*sqliteOutput) Description() string { return "buffered SQLite response recorder" }

// SetTestRunStopCallback stores k6's abort callback for recorder failures and
// load-duration completion; k6 installs it before Start.
func (o *sqliteOutput) SetTestRunStopCallback(stop func(error)) { o.stop = stop }

// Start opens the run database, publishes the active writer, and optionally
// starts authenticated load control and periodic progress reporting. Required
// paths and run metadata come from the output environment; setup errors fail startup.
func (o *sqliteOutput) Start() error {
	file := o.params.Environment["SQLITE_RECORDER_DB"]
	runID := o.params.Environment["SQLITE_RECORDER_RUN_ID"]
	if file == "" || runID == "" {
		return errors.New("SQLITE_RECORDER_DB and SQLITE_RECORDER_RUN_ID are required")
	}
	metadata := map[string]interface{}{}
	if raw := o.params.Environment["SQLITE_RECORDER_METADATA"]; raw != "" {
		if err := json.Unmarshal([]byte(raw), &metadata); err != nil {
			return err
		}
	}
	w, err := NewWriter(file, runID, DefaultSettings(), metadata)
	if err != nil {
		return err
	}
	w.SetStop(o.stop)
	o.writer = w
	o.progressFile = o.params.Environment["SQLITE_RECORDER_PROGRESS_FILE"]
	if o.progressFile != "" {
		o.progress = newProgressCollector(metadata)
	}
	active.Lock()
	active.writer = w
	active.Unlock()
	if file := o.params.Environment["SQLITE_RECORDER_CONTROL_FILE"]; file != "" {
		c, err := newLoadControl(metadata, file, o.params.Environment["SQLITE_RECORDER_CONTROL_TOKEN"], func() { o.stop(errors.New("console active load duration completed")) })
		if err != nil {
			_ = w.Close(err)
			return err
		}
		o.control = c
		active.Lock()
		active.control = c
		active.Unlock()
	}
	o.monitorStop = make(chan struct{})
	o.monitorDone = make(chan struct{})
	go func() {
		defer close(o.monitorDone)
		interval := 10 * time.Second
		if o.progressFile != "" {
			interval = time.Second
		}
		ticker := time.NewTicker(interval)
		defer ticker.Stop()
		for {
			select {
			case <-o.monitorStop:
				return
			case <-ticker.C:
				if o.progressFile != "" {
					o.writeProgress()
					continue
				}
				raw, _ := json.Marshal(w.Snapshot())
				fmt.Fprintf(o.params.StdErr, "SQLite recorder progress: %s\n", raw)
			}
		}
	}()
	return nil
}

// AddMetricSamples forwards k6 samples to live aggregation when a progress
// file was configured; database request capture uses the JavaScript API instead.
func (o *sqliteOutput) AddMetricSamples(samples []metrics.SampleContainer) {
	if o.progress != nil {
		o.progress.add(samples)
	}
}

// Stop finalizes recording when k6 supplies no test error, using the same
// drain and resource cleanup path as StopWithTestError.
func (o *sqliteOutput) Stop() error { return o.StopWithTestError(nil) }

// StopWithTestError stops progress polling, drains and closes the writer, then
// publishes final telemetry and releases load control. A controller-completed run
// with no in-flight work clears the stop error before completeness is evaluated.
func (o *sqliteOutput) StopWithTestError(err error) error {
	if o.writer == nil {
		return nil
	}
	close(o.monitorStop)
	<-o.monitorDone
	if o.control != nil && o.control.snapshot().State == "completed" && o.control.snapshot().InFlight == 0 {
		err = nil
	}
	result := o.writer.Close(recordingError(err))
	o.writeProgress()
	if o.control != nil {
		o.control.close()
	}
	stats := o.writer.Snapshot()
	raw, _ := json.Marshal(stats)
	fmt.Fprintf(o.params.StdErr, "SQLite recorder: %s\n", raw)
	active.Lock()
	active.writer = nil
	active.control = nil
	active.last = &stats
	active.Unlock()
	return result
}

// recordingError excludes thresholds evaluated after a finished test from
// recording completeness. Early threshold aborts and other interruptions remain
// errors because they may have truncated the captured workload.
func recordingError(err error) error {
	var reason errext.HasAbortReason
	if errors.As(err, &reason) && reason.AbortReason() == errext.AbortedByThresholdsAfterTestEnd {
		return nil
	}
	return err
}

// begin reserves an HTTP attempt before execution and classifies baseline and
// entity operations. started is a Unix-millisecond timestamp temporarily stored
// in LatencyMS; optional connectors identify the requested connector and MCA.
func begin(flowID string, merchantID *string, operation, method, url string, customerID, reference, paymentID *string, amount *int64, started int64, connectors ...string) (uint64, error) {
	w, err := current()
	if err != nil {
		return 0, err
	}
	role := "measured"
	if strings.HasPrefix(operation, "baseline_") {
		role = "baseline"
	}
	var entity *string
	if operation == "customer_create" {
		entity = strPointer("customer")
	}
	switch operation {
	case "payment_create", "payment_confirm", "baseline_create", "baseline_confirm", "baseline_poll":
		entity = strPointer("payment")
		if i := strings.Index(url, "/payments/"); i >= 0 {
			id := strings.SplitN(strings.SplitN(url[i+len("/payments/"):], "/", 2)[0], "?", 2)[0]
			if id != "" {
				paymentID = &id
			}
		} else if operation == "payment_create" || operation == "baseline_create" {
			paymentID = nil
		}
	}
	var requested, selected *string
	if len(connectors) > 0 && connectors[0] != "" {
		requested = &connectors[0]
	}
	if len(connectors) > 1 && connectors[1] != "" {
		selected = &connectors[1]
	}
	return w.Begin(Record{RequestedConnector: requested, SelectedConnectorAccount: selected, FlowID: flowID, MerchantID: merchantID, Operation: operation, Role: role, Method: method, URL: url,
		CustomerID: customerID, MerchantReferenceID: reference, PaymentID: paymentID, Amount: amount, ObservedAt: time.Now().UnixMilli(), LatencyMS: float64(started), EntityType: entity})
}

// finish submits an explicitly assembled result for a reserved attempt.
// The writer rejects unknown or previously finished attempt IDs.
func finish(id uint64, r Record) error {
	w, err := current()
	if err != nil {
		return err
	}
	return w.Finish(id, r)
}