Skip to content

Additional methods to a k6 modules API #2368

@olegbespalov

Description

@olegbespalov

What?

During the code review of the k6#2365 there was a suggestion about the improvement readability/maintainability of the logic that is sensible to the execution state (initial context or not).

There are plenty of places where we check this like:

state := c.vu.State()
if state == nil {
	return false, errConnectInInitContext
}

This looks okay, but it can be better if we introduce the additional method that will be just about the checking if we in the initial context.

For example it can be something, like:

if modules.InInitContext(c.vu) {
	return false, errConnectInInitContext
}

or since it depends on the property of the VU

if c.vu.InInitContext() {
	return false, errConnectInInitContext
}

Probably the same applies to a checking init environment:

initEnv := c.vu.InitEnv()
if initEnv == nil {
    return nil, errors.New("missing init environment")
}

There are plenty of places where we do this thing:

grep --exclude-dir=vendor -ER "if state == nil" ./       
./k6/js/modules/k6/http/request.go:	if state == nil {
./k6/js/modules/k6/http/request.go:	if state == nil {
./k6/js/modules/k6/http/request.go:	if state == nil {
./k6/js/modules/k6/k6.go:	if state == nil {
./k6/js/modules/k6/k6.go:	if state == nil {
./k6/js/modules/k6/ws/ws.go:	if state == nil {
./k6/js/modules/k6/metrics/metrics.go:	if state == nil {
./k6/js/modules/k6/grpc/client.go:	if state == nil {
./k6/js/modules/k6/grpc/client.go:	if state == nil {
grep --exclude-dir=vendor -ER "if initEnv == nil" ./
./js/modules/k6/metrics/metrics.go:	if initEnv == nil {
./js/modules/k6/grpc/client.go:	if initEnv == nil {

Why?

  • Having a dedicated method is more human-friendly since it explicitly names the case.
  • If we consolidate such checks, it will be better for the long term since we also improve the maintainability of the code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    evaluation neededproposal needs to be validated or tested before fully implementing it in k6refactor

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions