19#include <Poco/Net/StreamSocket.h>
20#include <Poco/Net/ServerSocket.h>
21#include <Poco/Net/DatagramSocket.h>
22#include <Poco/Net/SocketAddress.h>
23#include <Poco/Net/NetException.h>
24#include <Poco/Exception.h>
26#include <simplesquirrel/simplesquirrel.hpp>
36void callScript2(
const ssq::Object& obj, int64_t
a,
const std::string&
s) {
37 if (obj.isEmpty())
return;
38 ssq::Function
f = obj.toFunction();
39 if (
f.isEmpty())
return;
46void callScript3(
const ssq::Object& obj, int64_t
a, int64_t
b,
const std::string&
s) {
47 if (obj.isEmpty())
return;
48 ssq::Function
f = obj.toFunction();
49 if (
f.isEmpty())
return;
58 http_ = std::make_shared<HttpRuntime>();
59 worker_ = std::make_unique<NetWorker>(
this);
61 eve::cap::provide<eve::service::INetwork>(
this);
65 eve::cap::revoke<eve::service::INetwork>(
this);
67 if (worker_) worker_->stop();
71std::unique_ptr<TcpSocket>
Network::makeTcp() {
return std::make_unique<TcpSocket>(
this); }
74std::unique_ptr<UdpSocket>
Network::makeUdp() {
return std::make_unique<UdpSocket>(
this); }
78 return std::make_unique<HttpRequest>(
this, std::move(
method), std::move(url));
85 const std::string&
body,
int timeoutMs,
int&
status,
86 std::string& responseBody) {
92 req->
setTimeout(timeoutMs > 0 ? timeoutMs : 10000);
93 if (!req->
submit())
return false;
96 std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs > 0 ? timeoutMs : 10000);
97 while (std::chrono::steady_clock::now() <
deadline) {
101 recordSent(
result.sentBytes);
105 if (
c.bytes) responseBody.assign(
c.bytes->begin(),
c.bytes->end());
110 std::this_thread::sleep_for(std::chrono::milliseconds(10));
116 if (!socket)
return nullptr;
117 auto ch = std::make_unique<Channel>(socket);
118 bindChannel(socket, ch.get());
130 auto r = std::make_unique<NetReader>();
131 r->setBytes(std::move(
bytes));
137 if (!socket)
return nullptr;
138 auto link = std::make_unique<UdpLink>(
this, socket);
139 bindUdpLink(socket,
link.get());
145 return link ? std::make_unique<NetRpc>(
link) :
nullptr;
153 if (sock) udpLinks_[sock] =
link;
156void Network::unbindUdpLink(UdpSocket* sock) {
157 if (sock) udpLinks_.erase(sock);
160void Network::bindUdpHost(UdpSocket* sock, NetHost*
host) {
161 if (sock) udpHosts_[sock] =
host;
164void Network::unbindUdpHost(UdpSocket* sock) {
165 if (sock) udpHosts_.erase(sock);
180 ++telemetryRevision_;
182 receivedBytes_ +=
c.bytes->size();
187void Network::post(NetCompletion
c) {
189 if (worker_) worker_->post(std::move(
c));
192void Network::recordSent(
size_t bytes) {
194 ++telemetryRevision_;
200 result.sentBytes = sentBytes_.load();
201 result.receivedBytes = receivedBytes_.load();
202 result.completions = completions_.load();
203 result.errors = errors_.load();
204 result.connections = connections_.load();
206 std::lock_guard<std::mutex> lock(watchMu_);
207 result.watchedTcp = watchedTcp_.size();
208 result.watchedUdp = watchedUdp_.size();
209 for (
const auto* socket : watchedTcp_)
if (socket)
result.queuedTcpBytes += socket->pendingSendBytes();
212 std::lock_guard<std::mutex> lock(channelMu_);
213 result.channels = channels_.size();
219 sentBytes_ = receivedBytes_ = completions_ = errors_ = connections_ = 0;
220 ++telemetryRevision_;
223void Network::drainCompletions(std::vector<NetCompletion>&
out) {
224 if (worker_) worker_->drain(
out);
227void Network::watchTcp(TcpSocket* sock) {
228 std::lock_guard<std::mutex> lock(watchMu_);
229 if (std::find(watchedTcp_.begin(), watchedTcp_.end(), sock) == watchedTcp_.end()) {
230 watchedTcp_.push_back(sock);
231 ++telemetryRevision_;
235void Network::unwatchTcp(TcpSocket* sock) {
236 std::lock_guard<std::mutex> lock(watchMu_);
237 const auto before=watchedTcp_.size();
238 watchedTcp_.erase(std::remove(watchedTcp_.begin(), watchedTcp_.end(), sock), watchedTcp_.end());
239 if(before!=watchedTcp_.size())++telemetryRevision_;
242void Network::watchUdp(UdpSocket* sock) {
243 std::lock_guard<std::mutex> lock(watchMu_);
244 if (std::find(watchedUdp_.begin(), watchedUdp_.end(), sock) == watchedUdp_.end()) {
245 watchedUdp_.push_back(sock);
246 ++telemetryRevision_;
250void Network::unwatchUdp(UdpSocket* sock) {
251 std::lock_guard<std::mutex> lock(watchMu_);
252 const auto before=watchedUdp_.size();
253 watchedUdp_.erase(std::remove(watchedUdp_.begin(), watchedUdp_.end(), sock), watchedUdp_.end());
254 if(before!=watchedUdp_.size())++telemetryRevision_;
257void Network::bindChannel(TcpSocket* sock, Channel* ch) {
258 std::lock_guard<std::mutex> lock(channelMu_);
259 channels_[sock] = ch;
260 ++telemetryRevision_;
263void Network::unbindChannel(TcpSocket* sock) {
264 std::lock_guard<std::mutex> lock(channelMu_);
265 if(channels_.erase(sock))++telemetryRevision_;
268Channel* Network::channelFor(TcpSocket* sock)
const {
269 std::lock_guard<std::mutex> lock(channelMu_);
270 auto it = channels_.find(sock);
271 return it == channels_.end() ? nullptr : it->second;
274void Network::pollSockets() {
275 std::vector<TcpSocket*> tcpCopy;
277 std::lock_guard<std::mutex> lock(watchMu_);
278 tcpCopy = watchedTcp_;
282 if (sock->isListening() && sock->server()) {
284 Poco::Net::StreamSocket ss = sock->server()->acceptConnection();
285 ss.setBlocking(
false);
286 auto peer = std::make_unique<TcpSocket>(
this);
287 auto stream = std::make_unique<Poco::Net::StreamSocket>(ss);
288 peer->setConnectedSocket(std::move(stream));
290 sock->pushAccepted(std::move(peer));
297 c.peer =
raw->getPeer();
302 if (sock->isConnected() && sock->stream()) {
306 int n = sock->stream()->receiveBytes(buf,
sizeof(buf));
312 c.bytes = std::make_shared<std::vector<char>>(buf, buf +
n);
313 c.peer = sock->getPeer();
324 }
catch (
const Poco::Exception&) {
331 std::lock_guard<std::mutex> udpLock(watchMu_);
333 if (!sock || !sock->datagram())
continue;
334 for (
int i = 0; i < 64; ++i) {
337 Poco::Net::SocketAddress sender;
338 int n = sock->datagram()->receiveFrom(buf,
sizeof(buf), sender);
344 c.bytes = std::make_shared<std::vector<char>>(buf, buf +
n);
345 c.peer = sender.toString();
347 }
catch (
const Poco::Exception&) {
356void Network::emitCompletion(
const NetCompletion&
c) {
357 auto* ev = eve::ModuleManager::getInstance<eve::platform_event::PlatformEvent>(
"PlatformEvent");
363 std::vector<Variant> args;
366 args.push_back(Variant::makePtr(
c.handle));
367 args.push_back(Variant::makeString(
c.reason.empty() ?
"ok" :
c.reason));
368 ev->push(std::make_unique<Message>(
"netconn", args));
377 if (
c.bytes && !
c.bytes->empty())
379 args.push_back(Variant::makePtr(
c.handle));
380 args.push_back(Variant::makeOwnedPtr(bd));
381 args.push_back(Variant::makeString(
c.peer));
382 ev->push(std::make_unique<Message>(
"netdata", args));
388 args.push_back(Variant::makePtr(ch));
389 args.push_back(Variant::makeString(
c.reason));
390 ev->push(std::make_unique<Message>(
"chclose", args));
393 args.push_back(Variant::makePtr(
c.handle));
394 args.push_back(Variant::makeString(
c.reason));
395 ev->push(std::make_unique<Message>(
"neterr", args));
400 if (
c.bytes && !
c.bytes->empty())
402 args.push_back(Variant::makePtr(
c.handle));
403 args.push_back(Variant::makeInt(
c.status));
404 args.push_back(Variant::makeOwnedPtr(bd));
405 ev->push(std::make_unique<Message>(
"httpresp", args));
410 if (
c.bytes && !
c.bytes->empty())
412 args.push_back(Variant::makePtr(
c.handle));
413 args.push_back(Variant::makeOwnedPtr(bd));
414 ev->push(std::make_unique<Message>(
"chmsg", args));
418 args.push_back(Variant::makePtr(
c.handle));
419 args.push_back(Variant::makeString(
c.reason));
420 ev->push(std::make_unique<Message>(
"chclose", args));
426 std::vector<NetCompletion> batch;
427 drainCompletions(batch);
428 const int64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
429 std::chrono::steady_clock::now().time_since_epoch())
431 for (
auto&
c : batch) {
433 auto* sock =
static_cast<UdpSocket*
>(
c.handle);
434 auto hit = udpHosts_.find(sock);
435 if (
hit != udpHosts_.end()) {
436 if (
c.bytes)
hit->second->onDatagram(*
c.bytes,
c.peer);
439 auto lit = udpLinks_.find(sock);
440 if (lit != udpLinks_.end()) {
441 if (
c.bytes) lit->second->onDatagram(*
c.bytes,
c.peer);
447 for (
auto& kv : udpHosts_) kv.second->pump(now);
448 for (
auto& kv : udpLinks_) kv.second->pump(now);
449 std::vector<HttpResult> completed;
450 http_->drain(completed);
451 for (
auto&
result : completed) {
453 recordSent(
result.sentBytes);
454 recordCompletion(
result.completion);
455 emitCompletion(
result.completion);
459void Network::expose(ssq::Table& table) {
460 auto cls = table.addClass(
name, Network::create,
false);
464 "TcpSocket", std::function<TcpSocket*()>([]() {
return new TcpSocket(Network::create()); }),
true);
475 "UdpSocket", std::function<UdpSocket*()>([]() {
return new UdpSocket(Network::create()); }),
true);
486 std::function<HttpRequest*()>(
487 []() {
return new HttpRequest(Network::create(),
"GET",
"http://127.0.0.1/"); }),
498 "Channel", std::function<Channel*()>([]() {
return new Channel(
nullptr); }),
true);
503 auto sess =
table.addClass<Session>(
504 "Session", std::function<Session*()>([]() {
return new Session(); }),
true);
510 auto writer =
table.addClass<NetWriter>(
511 "NetWriter", std::function<NetWriter*()>([]() {
return new NetWriter(); }),
true);
512 writer.addFunc(
"writeU8", [](NetWriter*
w, int64_t
v) {
w->writeU8(
static_cast<uint8_t
>(
v)); });
513 writer.addFunc(
"writeI8", [](NetWriter*
w, int64_t
v) {
w->writeI8(
static_cast<int8_t
>(
v)); });
514 writer.addFunc(
"writeU16", [](NetWriter*
w, int64_t
v) {
w->writeU16(
static_cast<uint16_t
>(
v)); });
515 writer.addFunc(
"writeI16", [](NetWriter*
w, int64_t
v) {
w->writeI16(
static_cast<int16_t
>(
v)); });
516 writer.addFunc(
"writeU32", [](NetWriter*
w, int64_t
v) {
w->writeU32(
static_cast<uint32_t
>(
v)); });
517 writer.addFunc(
"writeI32", [](NetWriter*
w, int64_t
v) {
w->writeI32(
static_cast<int32_t
>(
v)); });
518 writer.addFunc(
"writeU64", [](NetWriter*
w, int64_t
v) {
w->writeU64(
static_cast<uint64_t
>(
v)); });
519 writer.addFunc(
"writeI64", [](NetWriter*
w, int64_t
v) {
w->writeI64(
static_cast<int64_t
>(
v)); });
525 if (
d)
w->writeBytes(
d->getData(),
d->getSize());
528 writer.addFunc(
"size", [](NetWriter*
w) {
return static_cast<int64_t
>(
w->size()); });
530 auto reader =
table.addClass<NetReader>(
531 "NetReader", std::function<NetReader*()>([]() {
return new NetReader(); }),
true);
533 return d ?
r->init(
d->getData(),
d->getSize()) : false;
535 reader.addFunc(
"initString", [](NetReader*
r,
const std::string&
s) {
return r->setBytes(
s); });
536 reader.addFunc(
"u8", [](NetReader*
r) {
return static_cast<int64_t
>(
r->u8()); });
537 reader.addFunc(
"i8", [](NetReader*
r) {
return static_cast<int64_t
>(
r->i8()); });
538 reader.addFunc(
"u16", [](NetReader*
r) {
return static_cast<int64_t
>(
r->u16()); });
539 reader.addFunc(
"i16", [](NetReader*
r) {
return static_cast<int64_t
>(
r->i16()); });
540 reader.addFunc(
"u32", [](NetReader*
r) {
return static_cast<int64_t
>(
r->u32()); });
541 reader.addFunc(
"i32", [](NetReader*
r) {
return static_cast<int64_t
>(
r->i32()); });
542 reader.addFunc(
"u64", [](NetReader*
r) {
return static_cast<int64_t
>(
r->u64()); });
543 reader.addFunc(
"i64", [](NetReader*
r) {
return static_cast<int64_t
>(
r->i64()); });
548 reader.addFunc(
"bytes", [](NetReader*
r, int64_t
n) {
549 auto v =
r->bytes(
static_cast<size_t>(
n));
550 return std::string(
v.data(),
v.size());
552 reader.addFunc(
"remaining", [](NetReader*
r) {
return static_cast<int64_t
>(
r->remaining()); });
553 reader.addFunc(
"pos", [](NetReader*
r) {
return static_cast<int64_t
>(
r->pos()); });
558 std::function<UdpLink*()>([]() {
return new UdpLink(
nullptr,
nullptr); }),
true);
561 link.addFunc(
"sendReliable", [](UdpLink* l, int64_t ch,
const std::string&
s) {
564 link.addFunc(
"sendUnreliable", [](UdpLink* l, int64_t ch,
const std::string&
s) {
567 link.addFunc(
"sendOrdered", [](UdpLink* l, int64_t ch,
const std::string&
s) {
570 link.addFunc(
"onMessage", [](UdpLink* l, ssq::Object
fn) {
572 l->setMessageHandler(
574 callScript2(
fn, ch, std::string(
d,
n));
579 link.addFunc(
"isAlive", [](UdpLink* l) {
return l && l->isAlive(); });
581 link.addFunc(
"peerId", [](UdpLink* l) {
return static_cast<int64_t
>(l->peerId()); });
582 link.addFunc(
"pendingReliable",
583 [](UdpLink* l) {
return static_cast<int64_t
>(l->pendingReliable()); });
584 link.addFunc(
"pendingFragments",
585 [](UdpLink* l) {
return static_cast<int64_t
>(l->pendingFragments()); });
587 auto rpc =
table.addClass<NetRpc>(
588 "NetRpc", std::function<NetRpc*()>([]() {
return new NetRpc(
nullptr); }),
true);
589 rpc.addFunc(
"callRpc", [](NetRpc*
r, int64_t msgId,
const std::string&
payload,
591 r->callString(
static_cast<uint16_t
>(msgId),
payload, reliable);
593 rpc.addFunc(
"registerRpc", [](NetRpc*
r, int64_t msgId, ssq::Object
fn) {
594 r->registerScript(
static_cast<uint16_t
>(msgId),
fn);
598 "NetHost", std::function<NetHost*()>([]() {
return new NetHost(
nullptr); }),
true);
602 h->setMessageHandler(
604 callScript3(
fn, peerId, ch, std::string(
d,
n));
609 h->setPeerConnectedHandler([
fn](uint32_t
id) { callScript2(
fn,
id,
""); });
611 host.addFunc(
"onPeerDisconnected", [](
NetHost*
h, ssq::Object
fn) {
613 h->setPeerDisconnectedHandler([
fn](uint32_t
id) { callScript2(
fn,
id,
""); });
615 host.addFunc(
"sendReliable", [](
NetHost*
h, int64_t peerId, int64_t ch,
616 const std::string&
s) {
618 static_cast<uint8_t
>(ch),
s);
620 host.addFunc(
"sendUnreliable", [](
NetHost*
h, int64_t peerId, int64_t ch,
621 const std::string&
s) {
623 static_cast<uint8_t
>(ch),
s);
625 host.addFunc(
"sendOrdered", [](
NetHost*
h, int64_t peerId, int64_t ch,
626 const std::string&
s) {
628 static_cast<uint8_t
>(ch),
s);
631 host.addFunc(
"peerCount", [](
NetHost*
h) {
return static_cast<int64_t
>(
h->peerCount()); });
636void Network::expose(ssq::Class&
cls) {
wgpu::PopErrorScopeStatus status
std::chrono::steady_clock::time_point deadline
#define Module_IMPL(ModuleName, newExpr)
The single Squirrel projection for common Result, Status and Value.
virtual std::string getName() const =0
Returns the name.
In-memory byte buffer implementing eve::Data (ref-counted).
Length-prefixed (big-endian uint32) message framing over a TcpSocket. sendMsg() writes one framed mes...
bool sendMsg(eve::data::ByteData *data)
Sends one framed message.
TcpSocket * getSocket() const
The underlying TCP socket, or nullptr.
bool sendMsgString(std::string s)
Sends a string payload as one framed message (empty strings are rejected).
Asynchronous HTTP request (Poco-based). Configure headers/body, call submit(), then receive the respo...
void setBodyString(std::string s)
Sets the request body as a string.
void setTimeout(int ms)
Overrides the module default timeout for this request (ms).
void setCaLocation(std::string location)
Overrides the CA file or hashed CA directory with an owning UTF-8 path. Empty selects system/default ...
void setBody(eve::data::ByteData *data)
Sets the request body bytes.
void setHeader(std::string k, std::string v)
Sets one request header.
bool submit()
Queues an immutable request snapshot; true reports acceptance only. @cost Starts a thread and perform...
void setVerifySsl(bool verify)
Overrides TLS verification for this request.
EVENGINE_API_PLATFORM public API.
void setLossRate(float rate)
Sets the loss rate.
bool start(uint16_t port)
Starts .
void setTimeoutMs(int ms)
Sets the timeout ms.
UdpLink * linkByPeerId(uint32_t peerId) const
Link by peer id.
EVENGINE_API_PLATFORM public API.
EVENGINE_API_PLATFORM public API.
EVENGINE_API_PLATFORM public API.
std::string toString() const
To string.
void writeBool(bool v)
Writes bool.
void writeF32(float v)
Writes f 32.
void writeString(const std::string &s)
Writes string.
void writeF64(double v)
Writes f 64.
Network module: TCP/UDP/HTTP factories, background worker, and completion event plumbing....
NetHost * newHost()
Script adapter: creates a caller-owned UDP host.
std::unique_ptr< TcpSocket > makeTcp()
Creates an owning TCP socket handle for C++ callers.
NetReader * newReader(std::string bytes)
Script adapter: creates a caller-owned reader.
std::unique_ptr< NetRpc > makeRpc(UdpLink *link)
Creates an owning RPC handle, or null for a null link.
bool getVerifySsl() const
Returns the verify ssl.
std::unique_ptr< NetReader > makeReader(std::string bytes)
Creates an owning streaming reader handle.
void setTimeout(int ms)
Default socket/HTTP timeout in milliseconds.
void setCaLocation(std::string location)
Sets an owning UTF-8 CA file or hashed CA directory for future HTTPS requests. Empty selects system/d...
Session * newSession()
Script adapter: creates a caller-owned session.
void resetTelemetry()
Reset cumulative telemetry counters without affecting live sockets.
std::unique_ptr< Session > makeSession()
Creates an owning session handle.
UdpLink * newUdpLink(UdpSocket *socket)
Script adapter: creates a caller-owned UDP link.
std::unique_ptr< NetWriter > makeWriter()
Creates an owning streaming writer handle.
std::unique_ptr< UdpSocket > makeUdp()
Creates an owning UDP socket handle for C++ callers.
void setVerifySsl(bool verify)
Whether TLS peer certificates are verified (default true).
std::unique_ptr< Channel > makeChannel(TcpSocket *socket)
Creates an owning channel handle, or null for a null socket.
bool httpRequest(const std::string &method, const std::string &url, const std::string &body, int timeoutMs, int &status, std::string &responseBody) override
Synchronous HTTP(S) compatibility service; other completions remain queued. @cost Blocks the owner th...
HttpRequest * newHttp(std::string method, std::string url)
Script adapter: creates a caller-owned HTTP request.
std::unique_ptr< HttpRequest > makeHttp(std::string method, std::string url)
Creates an owning HTTP request handle for C++ callers.
std::unique_ptr< NetHost > makeHost()
Creates an owning UDP host handle.
int getTimeout() const
Returns the timeout.
~Network() override
Cancels HTTP completions and joins background I/O before destruction. @cost May wait for in-flight so...
NetRpc * newRpc(UdpLink *link)
Script adapter: creates a caller-owned RPC client.
void pump()
Drains worker completions and emits them as events; call per frame.
NetWriter * newWriter()
Script adapter: creates a caller-owned writer.
UdpSocket * newUdp()
Script adapter: creates a caller-owned UDP socket.
TcpSocket * newTcp()
Script adapter: creates a caller-owned TCP socket.
std::unique_ptr< UdpLink > makeUdpLink(UdpSocket *socket)
Creates an owning UDP link handle, or null for a null socket.
NetTelemetrySnapshot telemetrySnapshot() const
Return a thread-safe copied telemetry snapshot for diagnostics tools.
Channel * newChannel(TcpSocket *socket)
Script adapter: creates a caller-owned channel.
Named collection of Channels (a "session"). Lookup by name, close all. Does not own the channels; the...
void remove(std::string name)
Removes a channel from the session (does not delete it).
void add(std::string name, Channel *ch)
Registers a channel under a name (replaces an existing entry).
void closeAll()
Closes every channel in the session.
Channel * get(std::string name)
Finds a channel by name, or nullptr.
TCP socket backed by Poco::Net; supports both client (connect) and server (listen/accept) roles....
bool listen(uint16_t port)
Starts listening on the given port; true on success.
bool sendString(std::string s)
Sends a string payload.
void close()
Closes the socket.
std::string getPeer() const
Remote peer address string, e.g. "1.2.3.4:5678".
TcpSocket * accept()
Accepts one pending client, or nullptr if none.
bool isConnected() const
True while a stream is connected.
bool connect(std::string host, uint16_t port)
Connects to host:port; true on success.
bool send(eve::data::ByteData *data)
Sends a framed byte payload; true when queued/accepted.
EVENGINE_API_PLATFORM public API.
bool setRemoteString(const std::string &addr)
bool setRemote(std::string host, uint16_t port)
MsgType
MsgType public API.
void setTimeoutMs(int ms)
void setLossRate(float rate)
UDP socket backed by Poco::Net; supports connect/bind and datagram send. @ownership The caller owns t...
bool sendTo(eve::data::ByteData *data, std::string host, uint16_t port)
Sends a datagram to an explicit host:port.
bool sendToString(std::string s, std::string host, uint16_t port)
Sends a string datagram to an explicit host:port.
void close()
Closes the socket.
bool bind(uint16_t port)
Binds to a local port; true on success.
bool sendString(std::string s)
Sends a string datagram to the connected peer.
bool connect(std::string host, uint16_t port)
Connects to a remote host:port (restricts send()).
bool send(eve::data::ByteData *data)
Sends a datagram to the connected peer.
std::unordered_map< std::string, SkillDefinition > & table()
SQRESULT callFunction(HSQUIRRELVM vm, const HSQOBJECT &fn, const Receiver &receiver, Args &&... args)
Call a script function, deriving sq_call's parameter count from the pushes.
void bindPointerMethod(ssq::Class &cls, const char *name, Pointer pointer, bool isStatic=false)
Binds a free/member function directly, without std::function or a heap wrapper.
constexpr RootTable rootTable
SettlementPipeline::Stage fn
One asynchronous network result/event. handle points at the originating TcpSocket/UdpSocket/HttpReque...
Copied aggregate counters for editor/profiler network inspection.