I am working on a k6 script where a series of REST API calls will be made along with a websocket endpoint connection. The websocket endpoint publishes latest data asynchronously from time to time.
The REST API calls will utilise the latest data available from the websocket.
Can we achieve this using k6?
I have created a sample script but I observe that k6 REST API calls block the websocket connection till REST API calls are not complete.
Is it possible to work with REST API calls, keep websocket connection active and work with latest data available from the socket?
The loop in below code is intended to replicate the situation created by series of REST API calls.
import { WebSocket } from 'k6/experimental/websockets';
import http from 'k6/http';
import { sleep, check } from 'k6';
export default function () {
let ws
init(ws)
for(let i=0;i<10;i++){
const response = http.get("https://test-api.k6.io/public/crocodiles/");
console.log(`Attempt ${i}: `,response.body)
sleep(10)
}
}
function init(ws) {
if (ws) {
ws.onerror = ws.onopen = ws.onclose = null;
ws.close();
}
ws = new WebSocket(`wss://test-api.k6.io/ws/crocochat/publicRoom/`);
ws.onopen = () => {
console.log('WebSocket connection established!');
ws.send(JSON.stringify({ event: 'SET_NAME', new_name: `Croc 6575:997` }));
console.log('Websocket message sent')
}
ws.onmessage = (data) => {
console.log(`a message received: ${JSON.stringify(data)}`);
};
ws.onclose = function() {
ws = null;
}
}
Response to this script is below:
INFO[0000] Attempt 0: ......
INFO[0011] Attempt 1: ......
....
....
....
INFO[0083] Attempt 8: ......
INFO[0093] Attempt 9: ...
INFO[0103] WebSocket connection established! source=console
INFO[0103] Websocket message sent source=console
INFO[0103] a message received: {"type":"message","target":{"url":"wss://test-api.k6.io/ws/crocochat/publicRoom/","readyState":1,"bufferedAmount":0,"binaryType":"ArrayBuffer"},"timestamp":1689744005564.149,"data":"{\"type\": \"send_message\", \"room\": \"publicRoom\", \"message\": \"anonymous joined\", \"user\": \"anonymous\", \"event\": \"USER_JOINED\"}","origin":"wss://test-api.k6.io/ws/crocochat/publicRoom/"} source=console
INFO[0103] a message received: {"type":"message","target":{"url":"wss://test-api.k6.io/ws/crocochat/publicRoom/","readyState":1,"bufferedAmount":0,"binaryType":"ArrayBuffer"},"timestamp":1689744108150.6484,"data":"{\"type\": \"send_message\", \"event\": \"NAME_CHANGE\", \"room\": \"publicRoom\", \"user\": \"Croc 6575:997\", \"message\": \"User anonymous changed name to 'Croc 6575:997'\"}","origin":"wss://test-api.k6.io/ws/crocochat/publicRoom/"} source=console