-
Notifications
You must be signed in to change notification settings - Fork 1k
Add support for Server Sent Events (SSE) #1274
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| #include "cpr/sse.h" | ||
|
|
||
| #include <charconv> | ||
| #include <utility> | ||
| #include <cstddef> | ||
| #include <functional> | ||
| #include <string> | ||
| #include <string_view> | ||
| #include <system_error> | ||
|
|
||
| namespace cpr { | ||
|
|
||
| bool ServerSentEventParser::parse(std::string_view data, const std::function<bool(ServerSentEvent&&)>& callback) { | ||
| // Append incoming data to buffer | ||
| buffer_.append(data); | ||
|
|
||
| // Process complete lines | ||
| size_t pos = 0; | ||
| while ((pos = buffer_.find('\n')) != std::string::npos) { | ||
| std::string line = buffer_.substr(0, pos); | ||
| buffer_.erase(0, pos + 1); | ||
|
|
||
| // Remove trailing \r if present (handles both \n and \r\n) | ||
| if (!line.empty() && line.back() == '\r') { | ||
| line.pop_back(); | ||
| } | ||
|
|
||
| if (!processLine(line, callback)) { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| void ServerSentEventParser::reset() { | ||
| buffer_.clear(); | ||
| current_event_ = ServerSentEvent(); | ||
| } | ||
|
|
||
| bool ServerSentEventParser::processLine(const std::string& line, const std::function<bool(ServerSentEvent&&)>& callback) { | ||
| // Empty line means end of event | ||
| if (line.empty()) { | ||
| return dispatchEvent(callback); | ||
| } | ||
|
|
||
| // Lines starting with ':' are comments, ignore them | ||
| if (line[0] == ':') { | ||
| return true; | ||
| } | ||
|
|
||
| // Find the colon separator | ||
| const size_t colon_pos = line.find(':'); | ||
|
|
||
| std::string field; | ||
| std::string value; | ||
|
|
||
| if (colon_pos == std::string::npos) { | ||
| // No colon, entire line is the field name | ||
| field = line; | ||
| value = ""; | ||
| } else { | ||
| field = line.substr(0, colon_pos); | ||
| // Skip the colon and optional leading space | ||
| size_t value_start = colon_pos + 1; | ||
| if (value_start < line.size() && line[value_start] == ' ') { | ||
| value_start++; | ||
| } | ||
| value = line.substr(value_start); | ||
| } | ||
|
|
||
| // Process the field | ||
| if (field == "event") { | ||
| current_event_.event = value; | ||
| } else if (field == "data") { | ||
| // Multiple data fields are concatenated with newlines | ||
| if (!current_event_.data.empty()) { | ||
| current_event_.data += '\n'; | ||
| } | ||
| current_event_.data += value; | ||
| } else if (field == "id") { | ||
| // Only set id if the value doesn't contain null character | ||
| if (value.find('\0') == std::string::npos) { | ||
| current_event_.id = value; | ||
| } | ||
| } else if (field == "retry") { | ||
| // Parse retry value as integer | ||
| size_t retry_value = 0; | ||
| const std::string_view sv(value); | ||
| auto [ptr, ec] = std::from_chars(sv.begin(), sv.end(), retry_value); | ||
| if (ec == std::errc()) { | ||
| current_event_.retry = retry_value; | ||
| } | ||
| } | ||
| // Unknown fields are ignored per spec | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| bool ServerSentEventParser::dispatchEvent(const std::function<bool(ServerSentEvent&&)>& callback) { | ||
| // Don't dispatch if data is empty | ||
| if (current_event_.data.empty()) { | ||
| current_event_ = ServerSentEvent(); | ||
| return true; | ||
| } | ||
|
|
||
| // Invoke callback with the current event | ||
| const bool continue_parsing = callback(std::move(current_event_)); | ||
|
|
||
| // Reset for next event (but keep event type as "message") | ||
| current_event_ = ServerSentEvent(); | ||
|
|
||
| return continue_parsing; | ||
| } | ||
|
|
||
| bool ServerSentEventCallback::handleData(std::string_view data) { | ||
| return parser_.parse(data, [this](ServerSentEvent&& event) { return (*this)(std::move(event)); }); | ||
| } | ||
|
|
||
| } // namespace cpr | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| #ifndef CPR_SSE_H | ||
| #define CPR_SSE_H | ||
|
|
||
| #include <cstdint> | ||
| #include <functional> | ||
| #include <utility> | ||
| #include <optional> | ||
| #include <string> | ||
| #include <string_view> | ||
|
|
||
| namespace cpr { | ||
|
|
||
| /** | ||
| * Represents a Server-Sent Event (SSE) as defined in the HTML5 specification. | ||
| * https://html.spec.whatwg.org/multipage/server-sent-events.html | ||
| */ | ||
| struct ServerSentEvent { | ||
| /** | ||
| * The event ID. Can be used to track the last received event and resume from there. | ||
| */ | ||
| std::optional<std::string> id; | ||
|
|
||
| /** | ||
| * The event type. If not specified, defaults to "message". | ||
| */ | ||
| std::string event{"message"}; | ||
|
|
||
| /** | ||
| * The event data. Multiple data fields are concatenated with newlines. | ||
| */ | ||
| std::string data; | ||
|
|
||
| /** | ||
| * The retry time in milliseconds. Used to set the reconnection time. | ||
| */ | ||
| std::optional<size_t> retry; | ||
|
|
||
| ServerSentEvent() = default; | ||
| }; | ||
|
|
||
| /** | ||
| * Parser for Server-Sent Events (SSE) streams. | ||
| * This parser handles incoming SSE data according to the HTML5 specification. | ||
| */ | ||
| class ServerSentEventParser { | ||
| public: | ||
| ServerSentEventParser() = default; | ||
|
|
||
| /** | ||
| * Parse incoming SSE data and invoke the callback for each complete event. | ||
| * @param data The incoming data chunk | ||
| * @param callback The callback to invoke for each parsed event | ||
| * @return true to continue receiving data, false to abort | ||
| */ | ||
| bool parse(std::string_view data, const std::function<bool(ServerSentEvent&&)>& callback); | ||
|
|
||
| /** | ||
| * Reset the parser state. | ||
| */ | ||
| void reset(); | ||
|
|
||
| private: | ||
| std::string buffer_; | ||
| ServerSentEvent current_event_; | ||
|
|
||
| bool processLine(const std::string& line, const std::function<bool(ServerSentEvent&&)>& callback); | ||
| bool dispatchEvent(const std::function<bool(ServerSentEvent&&)>& callback); | ||
| }; | ||
|
|
||
| /** | ||
| * Callback for handling Server-Sent Events. | ||
| * The callback receives each parsed SSE event and can return false to abort the connection. | ||
| */ | ||
| class ServerSentEventCallback { | ||
| public: | ||
| ServerSentEventCallback() = default; | ||
| // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) | ||
| ServerSentEventCallback(std::function<bool(ServerSentEvent&& event, intptr_t userdata)> p_callback, intptr_t p_userdata = 0) : userdata(p_userdata), callback(std::move(p_callback)) {} | ||
|
|
||
| bool operator()(ServerSentEvent&& event) const { | ||
| if (!callback) { | ||
| return true; | ||
| } | ||
| return callback(std::move(event), userdata); | ||
| } | ||
|
|
||
| /** | ||
| * Internal function used to handle raw data chunks and parse them into SSE events. | ||
| * This is called by the underlying write callback mechanism. | ||
| */ | ||
| bool handleData(std::string_view data); | ||
|
|
||
| intptr_t userdata{}; | ||
| std::function<bool(ServerSentEvent&& event, intptr_t userdata)> callback; | ||
|
|
||
| private: | ||
| ServerSentEventParser parser_; | ||
| }; | ||
|
|
||
| } // namespace cpr | ||
|
|
||
| #endif |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.