Rise
The Vieneo Province
Loading...
Searching...
No Matches
CloudWeatherReceiver.h
Go to the documentation of this file.
1#pragma once
3#include <condition_variable>
4#include <deque>
5#include <mutex>
6#include <thread>
7
8namespace CloudWeather
9{
10 // Network dispatch copies bounded chunks only. One worker assembles,
11 // validates, decompresses and builds the mip chain before publication.
13 {
14 std::mutex mutex;
15 std::condition_variable wake;
16 std::deque<std::vector<uint8_t>> queue;
18 uint64_t epoch = 0;
19 bool stopping = false;
20 std::thread worker;
21 void Run()
22 {
23 Assembler assembler;
24 uint64_t assemblingEpoch = 0;
25 for (;;)
26 {
27 std::vector<uint8_t> packet; uint64_t packetEpoch;
28 {
29 std::unique_lock<std::mutex> lock(mutex);
30 wake.wait(lock, [&] { return stopping || !queue.empty(); });
31 if (stopping) return;
32 packetEpoch = epoch; packet = std::move(queue.front()); queue.pop_front();
33 }
34 if (assemblingEpoch != packetEpoch) { assembler.Reset(); assemblingEpoch = packetEpoch; }
35 MapPtr map;
36 try { map = assembler.Accept(packet.data(), packet.size()); }
37 catch (...) { assembler.Reset(); } // reject a failed allocation without killing networking
38 if (map)
39 {
40 std::lock_guard<std::mutex> lock(mutex);
41 if (epoch == packetEpoch && (!latest || map->revision > latest->revision)) latest = std::move(map);
42 }
43 }
44 }
45 public:
46 Receiver() :worker([this] { Run(); }) {}
47 ~Receiver() { { std::lock_guard<std::mutex> lock(mutex); stopping = true; } wake.notify_one(); worker.join(); }
48 void Reset() { std::lock_guard<std::mutex> lock(mutex); ++epoch; queue.clear(); latest.reset(); }
49 MapPtr Latest() { std::lock_guard<std::mutex> lock(mutex); return latest; }
50 bool Submit(const uint8_t* packet, size_t size)
51 {
52 Header header;
53 if (!Parse(packet, size, header)) return false;
54 std::lock_guard<std::mutex> lock(mutex);
55 if (queue.size() >= 1024) return false; // <=16 MiB regardless of sender
56 queue.emplace_back(packet, packet + size); wake.notify_one(); return true;
57 }
58 };
59}
MapPtr Accept(const uint8_t *packet, size_t size)
bool Submit(const uint8_t *packet, size_t size)
std::condition_variable wake
std::deque< std::vector< uint8_t > > queue
bool Parse(const uint8_t *p, size_t length, Header &h)
std::shared_ptr< const Map > MapPtr