Reconnect in VU

In self-written plugin “examplePlugin”, I have a connection to a server. this is a very slow operation.
I do this once at startup. Then I’ll reuse this connection. If there is a failure, I need to reconnect, but I don’t understand how to do this, since I can’t update “let conn” state from the “export function send_msg(){}” block.
I also couldn’t find this case in the documentation k6

import customPlugin from "k6/x/examplePlugin";

let conn = customPlugin.connect()

export function send_msg() {
 conn.send_msg()
}

Hi @chipartem :wave:

Welcome to the support forum :tada:

I think some background information to guide you to a solution might be necessary here :slight_smile:

Background

In the example you have posted, k6 treats the two existing JavaScript scopes in very different ways:

let conn = customPlugin.connect()

It happens in the “init context” and is executed a single time by each VU. Every time it is executed and a connection is instantiated, the connection object lives in a specific VU. That means if you run a test with 10 VUs, each VU will have a different connection object.

Thus,

// Each VU performs this step 👇 and ends up with its own
// dedicated instance of the connection.
let conn = customPlugin.connect()

export function send_msg() {
  // As we are now in the VU context, this code uses the VU
  // connection object.
 conn.send_msg()
}

Although it might look like it, the conn object you define at the top is thus not a unique and shared object across all the VUs, and each of them, instead, instantiates its own copy independently.

We have documented the various lifecycle specificities and guarantees in the documentation: Test lifecycle
I believe it might help you find solutions to your issue.

Solution space

Now, my understanding is that you would like to attempt reconnecting if/when the connection is lost.

If you’re fine with having one connection per VU as described above, making some check in the default function whether there’s a need to reconnect might help:

let conn = customPlugin.connect()

export function send_msg() {
  if (!conn.connected) {
    conn.connect()
  }

 conn.send_msg()
}

But depending on what you do in the rest of your load test, that could skew the results. It really depends.

Let me know if that’s helpful and if I can provide more information and support :bowing_man:

2 Likes