pulsatrix 1.1.0
Loading...
Searching...
No Matches
sse.hpp
Go to the documentation of this file.
1
5#pragma once
6
7#include <chrono>
8#include <cstddef>
9#include <functional>
10#include <optional>
11#include <string>
12#include <string_view>
13
14namespace pulsatrix::orch {
15
17struct SseEvent {
19 std::string type = "message";
21 std::string data;
23 std::string last_event_id;
24};
25
34class SseParser {
35public:
36 using Handler = std::function<void(const SseEvent&)>;
37
42 explicit SseParser(Handler on_event, std::size_t max_event_bytes = std::size_t{16} << 20);
43
46 void feed(std::string_view chunk);
47
50 void finish();
51
53 [[nodiscard]] std::optional<std::chrono::milliseconds> retry() const { return retry_; }
54
55private:
56 void process_line(std::string_view line);
57 void dispatch();
58
59 Handler on_event_;
60 std::size_t max_event_bytes_;
61 std::string line_;
62 std::string data_;
63 std::string type_;
64 std::string last_event_id_;
65 std::optional<std::chrono::milliseconds> retry_;
66 bool after_cr_ = false; // the last chunk ended in CR, so a leading LF finishes that line
67 bool started_ = false; // past the position where a byte-order mark may appear
68 std::size_t bom_matched_ = 0;
69 bool has_data_ = false;
70};
71
72} // namespace pulsatrix::orch
Parses a text/event-stream body fed in chunks of any size, as the WHATWG HTML specification defines i...
Definition sse.hpp:34
void feed(std::string_view chunk)
Parses chunk, calling the handler for every event it completes.
std::optional< std::chrono::milliseconds > retry() const
The reconnection time from the last valid retry: field, if any.
Definition sse.hpp:53
SseParser(Handler on_event, std::size_t max_event_bytes=std::size_t{16}<< 20)
std::function< void(const SseEvent &)> Handler
Definition sse.hpp:36
void finish()
The end of the stream. An event without its closing blank line is discarded, as the specification req...
Definition http.hpp:20
One server-sent event.
Definition sse.hpp:17
std::string type
The event: field, or message when the event has none.
Definition sse.hpp:19
std::string last_event_id
The last id: seen in the stream so far, as the specification defines it.
Definition sse.hpp:23
std::string data
The data: lines joined with newlines.
Definition sse.hpp:21