Files
firesse/stream.cc

55 lines
1.1 KiB
C++
Raw Permalink Normal View History

2019-05-05 00:11:57 -07:00
#include "stream.h"
#include "index.h"
2019-05-05 00:11:57 -07:00
namespace firesse {
Stream::Stream(firecgi::Request* request, Index* index)
2019-05-18 12:18:26 -07:00
: request_(request), index_(index) {
index_->Add(this);
}
Stream::~Stream() {
2019-05-18 12:18:26 -07:00
std::lock_guard l(mu_);
index_->Remove(this);
}
void Stream::OnClose(const std::function<void()>& callback) {
2019-05-18 12:18:26 -07:00
on_close_ = callback;
}
2019-05-05 00:11:57 -07:00
2019-05-18 12:18:26 -07:00
bool Stream::WriteEvent(const std::string_view& data, uint64_t id,
const std::string& type) {
std::lock_guard l(mu_);
index_->Freshen(this);
return request_->InTransaction<bool>([=]() {
if (id) {
request_->WriteBody("id: ", std::to_string(id), "\n");
}
if (!type.empty()) {
request_->WriteBody("event: ", type, "\n");
}
request_->WriteBody("data: ", data, "\n\n");
return request_->Flush();
});
2019-05-05 00:11:57 -07:00
}
bool Stream::WriteRaw(const std::string_view& data) {
2019-05-18 12:18:26 -07:00
std::lock_guard l(mu_);
2019-05-18 12:18:26 -07:00
request_->WriteBody(data);
return request_->Flush();
}
2019-05-18 12:18:26 -07:00
bool Stream::End() { return request_->End(); }
2019-05-05 00:11:57 -07:00
2019-05-11 22:27:33 -07:00
void Stream::Close() {
2019-05-18 12:18:26 -07:00
if (on_close_) {
on_close_();
}
2019-05-11 22:27:33 -07:00
}
2019-05-18 12:18:26 -07:00
} // namespace firesse