SSE (Server Sent Event)
Learn the possible SSE operations with Gatling: connect, close.
SSE support is an extension to the HTTP SDK, whose entry point is the sse(requestName: Expression[String]) method.
sseName
If you want to deal with several SSE streams per virtual users, you have to give them a name and pass this name on each SSE operation: For example:
sse("Sse").sseName("myCustomName");sse("Sse").sseName("myCustomName");sse("Sse").sseName("myCustomName")sse("Sse").sseName("myCustomName")Of course, this step is not required if you deal with one single SSE stream per virtual user.
Connecting
The first thing is to connect the stream:
Gatling supports GET and POST requests:
exec(sse("Connect").get("/stocks/prices"));
exec(sse("Connect").post("/stocks/prices").body(StringBody("{\"foo\": \"bar\"}")));exec(sse("Connect").get("/stocks/prices"));
exec(sse("Connect").post("/stocks/prices").body(StringBody("{\"foo\": \"bar\"}")));exec(sse("Connect").get("/stocks/prices"))
exec(sse("Connect").post("/stocks/prices").body(StringBody("{\"foo\": \"bar\"}")))exec(sse("Connect").get("/stocks/prices"))
exec(sse("Connect").post("/stocks/prices").body(StringBody("""{"foo": "bar"}""")))Accept header to text/event-stream and Cache-Control to no-cache.close
Once you’re done with a SSE stream, you can close it.
exec(sse("Close").close());exec(sse("Close").close());exec(sse("Close").close())exec(sse("Close").close)Checks
You deal with incoming messages with checks.
By default, a check only matches the messages received after it’s set. To also match messages received earlier, see Match messages received before setting a check.
Gatling currently only supports blocking checks that will wait until receiving expected message or timing out.
When using SSE checks, Stream Events get turned into JSON, eg
id: 77535
event: snapshot
data: [{"symbol":"BTC","price":4628.27},{"symbol":"ETH","price":3249.19}]
is turned into:
{
"id": "77535",
"event": "snapshot",
"data": [
{"symbol":"BTC","price":4628.27},
{"symbol":"ETH","price":3249.19}
]
}
This way, you can apply checks on any Stream field with jsonPath and jmesPath.
Set a check
You can set a check right after connecting:
exec(sse("Connect").get("/stocks/prices")
.await(5).on(sseCheck));exec(sse("Connect").get("/stocks/prices")
.await(5).on(sseCheck));exec(sse("Connect").get("/stocks/prices")
.await(5).on(sseCheck))exec(sse("Connect").get("/stocks/prices")
.await(5)(sseCheck))Or you can set a check from main flow:
exec(sse("SetCheck").setCheck()
.await(30).on(sseCheck));exec(sse("SetCheck").setCheck()
.await(30).on(sseCheck));exec(sse("SetCheck").setCheck()
.await(30).on(sseCheck))exec(sse("SetCheck").setCheck
.await(30)(sseCheck))You can set multiple checks sequentially. Each one will expect one single frame.
You can configure multiple checks in a single sequence:
// expecting 2 messages
// 1st message will be validated against sseCheck1
// 2nd message will be validated against sseCheck2
// whole sequence must complete withing 30 seconds
exec(sse("SetCheck").setCheck()
.await(30).on(sseCheck1, sseCheck2));// expecting 2 messages
// 1st message will be validated against sseCheck1
// 2nd message will be validated against sseCheck2
// whole sequence must complete withing 30 seconds
exec(sse("SetCheck").setCheck()
.await(30).on(sseCheck1, sseCheck2));// expecting 2 messages
// 1st message will be validated against sseCheck1
// 2nd message will be validated against sseCheck2
// whole sequence must complete withing 30 seconds
exec(sse("SetCheck").setCheck()
.await(30).on(sseCheck, sseCheck))// expecting 2 messages
// 1st message will be validated against sseCheck1
// 2nd message will be validated against sseCheck2
// whole sequence must complete withing 30 seconds
exec(sse("SetCheck").setCheck
.await(30)(sseCheck1, sseCheck2))You can also configure multiple check sequences with different timeouts:
// expecting 2 messages
// 1st message will be validated against sseCheck1
// 2nd message will be validated against sseCheck2
// both sequences must complete withing 15 seconds
// 2nd sequence will start after 1st one completes
exec(sse("SetCheck").setCheck()
.await(15).on(sseCheck1)
.await(15).on(sseCheck2));// expecting 2 messages
// 1st message will be validated against sseCheck1
// 2nd message will be validated against sseCheck2
// both sequences must complete withing 15 seconds
// 2nd sequence will start after 1st one completes
exec(sse("SetCheck").setCheck()
.await(15).on(sseCheck1)
.await(15).on(sseCheck2));// expecting 2 messages
// 1st message will be validated against sseCheck1
// 2nd message will be validated against sseCheck2
// both sequences must complete withing 15 seconds
// 2nd sequence will start after 1st one completes
exec(sse("SetCheck").setCheck()
.await(15).on(sseCheck)
.await(15).on(sseCheck))// expecting 2 messages
// 1st message will be validated against sseCheck1
// 2nd message will be validated against sseCheck2
// both sequences must complete withing 15 seconds
// 2nd sequence will start after 1st one completes
exec(sse("SetCheck").setCheck
.await(15)(sseCheck1)
.await(15)(sseCheck2))Match messages received before setting a check
By default, a setCheck only matches the messages received after it’s set.
If the expected message arrives earlier, for example as a consequence of a previous HTTP request, the setCheck times out.
To prevent this, enable the setCheck buffer on the HttpProtocol with sseSetCheckBuffer(maxSize, maxAge):
| Parameter | Description |
|---|---|
maxSize |
The maximum number of buffered messages. When the buffer is full, Gatling drops the oldest message. Must be strictly positive. |
maxAge |
The maximum age of buffered messages. Gatling drops older messages. Must be strictly positive. |
http
// buffer up to 100 inbound events that no check matched,
// for up to 10 seconds
.sseSetCheckBuffer(100, Duration.ofSeconds(10));
exec(
// trigger an event on the stream
http("Place order").post("/orders"),
// the event might have already arrived: setCheck matches it from the buffer
sse("Wait for the event").setCheck().await(30).on(sseCheck)
);http
// buffer up to 100 inbound events that no check matched,
// for up to 10 seconds
.sseSetCheckBuffer(100, 10);
exec(
// trigger an event on the stream
http("Place order").post("/orders"),
// the event might have already arrived: setCheck matches it from the buffer
sse("Wait for the event").setCheck().await(30).on(sseCheck)
);http
// buffer up to 100 inbound events that no check matched,
// for up to 10 seconds
.sseSetCheckBuffer(100, Duration.ofSeconds(10))
exec(
// trigger an event on the stream
http("Place order").post("/orders"),
// the event might have already arrived: setCheck matches it from the buffer
sse("Wait for the event").setCheck().await(30).on(sseCheck)
)http
// buffer up to 100 inbound events that no check matched,
// for up to 10 seconds
.sseSetCheckBuffer(100, 10.seconds)
exec(
// trigger an event on the stream
http("Place order").post("/orders"),
// the event might have already arrived: setCheck matches it from the buffer
sse("Wait for the event").setCheck.await(30)(sseCheck)
)With the buffer enabled:
- Gatling buffers the inbound messages that no check matched: the messages received while no check is pending, and the messages that don’t match the pending check.
- When you call
setCheck, Gatling first replays the buffered messages against the new checks, oldest first, as if they were received when the check was set. Matched messages leave the buffer, and the other ones stay for the nextsetCheck. - When a check of a sequence passes, Gatling retries the buffered messages that didn’t match it against the next checks of the sequence.
- When the stream automatically reconnects, Gatling keeps the buffer, as the stream resumes from the last received event ID (
Last-Event-ID).
Only setCheck replays buffered messages: checks set on get or post only match messages received after connecting.
This buffer is independent from the one used by processUnmatchedMessages.
sseSetCheckBuffer is available since Gatling 3.16.1 and the JavaScript and TypeScript SDK 3.16.101.Create a check
You can create checks for server events with checkMessage.
You can use almost all the same check criteria as for HTTP requests.
SseMessageCheck sseCheck = sse.checkMessage("checkName")
.check(regex("event: snapshot(.*)"));const sseCheck = sse.checkMessage("checkName")
.check(regex("event: snapshot(.*)"));val sseCheck = sse.checkMessage("checkName")
.check(regex("event: snapshot(.*)"))val sseCheck = sse.checkMessage("checkName")
.check(regex("event: snapshot(.*)"))You can have multiple criteria for a given message:
sse.checkMessage("checkName")
.check(
regex("event: event1(.*)"),
regex("event: event2(.*)")
);sse.checkMessage("checkName")
.check(
regex("event: event1(.*)"),
regex("event: event2(.*)")
);sse.checkMessage("checkName")
.check(
regex("event: event1(.*)"),
regex("event: event2(.*)")
)sse.checkMessage("checkName")
.check(
regex("event: event1(.*)"),
regex("event: event2(.*)")
)You can also apply a function on the Session resulting from the check, after it’s been applied, with postCheck.
Throw an exception to make the check fail with the exception’s message (in Scala, the function returns a Validation: a Success wrapping the new Session, or a Failure).
sse.checkMessage("checkName")
.check(regex("event: event1(.*)").saveAs("event1"))
.postCheck(session -> {
if (!session.contains("foo")) {
throw new IllegalStateException("foo is missing");
}
return session.set("bar", 1);
});sse.checkMessage("checkName")
.check(regex("event: event1(.*)").saveAs("event1"))
.postCheck((session) => {
if (!session.contains("foo")) {
throw new Error("foo is missing");
}
return session.set("bar", 1);
});sse.checkMessage("checkName")
.check(regex("event: event1(.*)").saveAs("event1"))
.postCheck({ session ->
if (!session.contains("foo")) {
throw IllegalStateException("foo is missing")
}
session.set("bar", 1)
})sse.checkMessage("checkName")
.check(regex("event: event1(.*)").saveAs("event1"))
.postCheck(session => {
if (!session.contains("foo")) {
Failure("foo is missing")
} else {
Success(session.set("bar", 1))
}
})Apply checks conditionally
Use checkIf to apply checks only when a condition holds.
The condition is a Gatling Expression Language String that resolves a Boolean, or a function of the Session and, optionally, of the inbound message (the event, as a JSON String).
// with a Gatling EL String condition that resolves a Boolean
sse.checkMessage("checkName")
.checkIf("#{bool}")
.then(jsonPath("$.data").saveAs("snapshot"));
// with a function aware of the Session
sse.checkMessage("checkName")
.checkIf(session -> session.getString("key").equals("executeCheck"))
.then(jsonPath("$.data").saveAs("snapshot"));
// with a function aware of the message and of the Session
sse.checkMessage("checkName")
.checkIf((message, session) -> message.contains(session.getString("symbol")))
.then(jsonPath("$.data").saveAs("snapshot"));// with a Gatling EL String condition that resolves a Boolean
sse.checkMessage("checkName")
.checkIf("#{bool}")
.then(jsonPath("$.data").saveAs("snapshot"));
// with a function aware of the Session
sse.checkMessage("checkName")
.checkIf((session) => session.get("key") === "executeCheck")
.then(jsonPath("$.data").saveAs("snapshot"));
// with a function aware of the Session and of the message: the Session comes first
sse.checkMessage("checkName")
.checkIf((session, message) => message.includes(session.get("symbol")))
.then(jsonPath("$.data").saveAs("snapshot"));// with a Gatling EL String condition that resolves a Boolean
sse.checkMessage("checkName")
.checkIf("#{bool}")
.then(jsonPath("$.data").saveAs("snapshot"))
// with a function aware of the Session
sse.checkMessage("checkName")
.checkIf { session -> session.getString("key") == "executeCheck" }
.then(jsonPath("$.data").saveAs("snapshot"))
// with a function aware of the message and of the Session
sse.checkMessage("checkName")
.checkIf { message, session -> message.contains(session.getString("symbol")!!) }
.then(jsonPath("$.data").saveAs("snapshot"))// with a Gatling EL String condition that resolves a Boolean
sse.checkMessage("checkName")
.checkIf("#{bool}")(jsonPath("$.data").saveAs("snapshot"))
// with a function aware of the Session
sse.checkMessage("checkName")
.checkIf(session => session("key").as[String] == "executeCheck")(jsonPath("$.data").saveAs("snapshot"))
// with a function aware of the message and of the Session
sse.checkMessage("checkName")
.checkIf((message, session) => message.contains(session("symbol").as[String]))(jsonPath("$.data").saveAs("snapshot"))(session) => … or (session, message) => ….
In Java, Kotlin, and Scala, the message comes first: (message, session).Matching messages
You can define matching criteria to filter messages you want to check.
Matching criterion is a standard check, except it doesn’t take saveAs.
Non-matching messages will be ignored.
exec(sse("SetCheck").setCheck()
.await(1).on(
sse.checkMessage("checkName")
.matching(jmesPath("event").is("snapshot"))
.check(jmesPath("id").ofInt().is(77535))
));exec(sse("SetCheck").setCheck()
.await(1).on(
sse.checkMessage("checkName")
.matching(jmesPath("event").is("snapshot"))
.check(jmesPath("id").ofInt().is(77535))
));exec(sse("SetCheck").setCheck()
.await(1).on(
sse.checkMessage("checkName")
.matching(jmesPath("event").shouldBe("snapshot"))
.check(jmesPath("id").ofInt().shouldBe(77535))
))exec(sse("SetCheck").setCheck
.await(1)(
sse.checkMessage("checkName")
.matching(jmesPath("event").is("snapshot"))
.check(jmesPath("id").ofType[Int].is(77535))
))Processing unmatched messages
You can use processUnmatchedMessages to process inbound messages that haven’t been matched with a check and have been buffered.
By default, unmatched inbound messages are not buffered, you must enable this feature by setting the size of the buffer on the protocol with .sseUnmatchedInboundMessageBufferSize(maxSize).
The buffer is reset when:
- sending an outbound message
- calling
processUnmatchedMessagesso we don’t present the same message twice
You can then pass your processing logic as a function.
The list of messages passed to this function is sorted in timestamp ascending (meaning older messages first).
It contains instances of types io.gatling.http.action.sse.SseInboundMessage.
Reminder: messages are JSON string versions of the events.
// store the unmatched messages in the Session
sse.processUnmatchedMessages((messages, session) -> session.set("messages", messages));
// collect the last message and store it in the Session
sse.processUnmatchedMessages((messages, session) ->
!messages.isEmpty()
? session.set("lastMessage", messages.get(messages.size() - 1).message())
: session
);// store the unmatched messages in the Session
sse.processUnmatchedMessages((messages, session) => session.set("messages", messages))
// collect the last message and store it in the Session
sse.processUnmatchedMessages((messages, session) =>
messages.length != 0
? session.set("lastMessage", messages[messages.length - 1].message())
: session
);// store the unmatched messages in the Session
sse.processUnmatchedMessages { messages, session -> session.set("messages", messages) }
// collect the last message and store it in the Session
sse.processUnmatchedMessages { messages, session ->
if (messages.isNotEmpty()) session.set("lastMessage", messages.last().message())
else session
}// store the unmatched messages in the Session
sse.processUnmatchedMessages((messages, session) => session.set("messages", messages))
// collect the last message and store it in the Session
sse.processUnmatchedMessages { (messages, session) =>
messages
.lastOption
.fold(session)(m => session.set("lastMessage", m.message))
}Configuration
SSE support introduces new HttpProtocol parameters:
http
// enable unmatched SSE inbound messages buffering,
// with a max buffer size of 5
.sseUnmatchedInboundMessageBufferSize(5);http
// enable unmatched SSE inbound messages buffering,
// with a max buffer size of 5
.sseUnmatchedInboundMessageBufferSize(5);http
// enable unmatched SSE inbound messages buffering,
// with a max buffer size of 5
.sseUnmatchedInboundMessageBufferSize(5)http
// enable unmatched SSE inbound messages buffering,
// with a max buffer size of 5
.sseUnmatchedInboundMessageBufferSize(5)Debugging
You can inspect streams if you add the following logger to your logback configuration:
<logger name="io.gatling.http.action.sse.fsm" level="DEBUG" />
Example
Here’s an example that runs against a stock market sample:
ScenarioBuilder scn = scenario("ServerSentEvents")
.exec(
sse("Stocks").get("/stocks/prices")
.await(10).on(
sse.checkMessage("checkName").check(jmesPath("event").is("snapshot"))
),
pause(15),
sse("Close").close()
);const scn = scenario("ServerSentEvents")
.exec(
sse("Stocks").get("/stocks/prices")
.await(10).on(
sse.checkMessage("checkName").check(jmesPath("event").is("snapshot"))
),
pause(15),
sse("Close").close()
);val scn = scenario("ServerSentEvents")
.exec(
sse("Stocks").get("/stocks/prices")
.await(10).on(
sse.checkMessage("checkName").check(jmesPath("event").shouldBe("snapshot"))
),
pause(15),
sse("Close").close()
)val scn = scenario("ServerSentEvents")
.exec(
sse("Stocks").get("/stocks/prices")
.await(10)(
sse.checkMessage("checkName").check(jmesPath("event").is("snapshot"))
),
pause(15),
sse("Close").close
)