载入中...
搜索中...
未找到
Network.cpp
浏览该文件的文档.
1// eve-hot-path: completion pumping and transport telemetry.
2#include "network/Network.h"
5#include "data/ByteData.h"
6#include "network/Channel.h"
8#include "network/NetHost.h"
9#include "network/NetRpc.h"
10#include "network/NetStream.h"
11#include "network/NetWorker.h"
12#include "network/Session.h"
13#include "network/TcpSocket.h"
14#include "network/UdpLink.h"
15#include "network/UdpSocket.h"
18
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>
25
26#include <simplesquirrel/simplesquirrel.hpp>
27#include <algorithm>
28#include <chrono>
29#include <functional>
30#include <thread>
31
32namespace eve::network {
33
34namespace {
35
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;
40 // Receiver is the root table; the count is derived and a failing callback is
41 // reported. This call used to discard sq_call's result outright, so a broken
42 // network callback was invisible.
43 (void)script::callFunction(f.getHandle(), f.getRaw(), script::rootTable, a, s);
44}
45
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;
50 (void)script::callFunction(f.getHandle(), f.getRaw(), script::rootTable, a, b, s);
51}
52
53} // namespace
54
56
58 http_ = std::make_shared<HttpRuntime>();
59 worker_ = std::make_unique<NetWorker>(this);
60 worker_->start();
61 eve::cap::provide<eve::service::INetwork>(this);
62}
63
65 eve::cap::revoke<eve::service::INetwork>(this);
66 http_->close();
67 if (worker_) worker_->stop();
68 worker_.reset();
69}
70
71std::unique_ptr<TcpSocket> Network::makeTcp() { return std::make_unique<TcpSocket>(this); }
72TcpSocket* Network::newTcp() { return makeTcp().release(); }
73
74std::unique_ptr<UdpSocket> Network::makeUdp() { return std::make_unique<UdpSocket>(this); }
75UdpSocket* Network::newUdp() { return makeUdp().release(); }
76
77std::unique_ptr<HttpRequest> Network::makeHttp(std::string method, std::string url) {
78 return std::make_unique<HttpRequest>(this, std::move(method), std::move(url));
79}
80HttpRequest* Network::newHttp(std::string method, std::string url) {
81 return makeHttp(std::move(method), std::move(url)).release();
82}
83
84bool Network::httpRequest(const std::string& method, const std::string& url,
85 const std::string& body, int timeoutMs, int& status,
86 std::string& responseBody) {
87 status = 0;
88 responseBody.clear();
89 auto ownedRequest = makeHttp(method, url);
90 HttpRequest* req = ownedRequest.get();
91 if (!body.empty()) req->setBodyString(body);
92 req->setTimeout(timeoutMs > 0 ? timeoutMs : 10000);
93 if (!req->submit()) return false;
94
95 const auto deadline =
96 std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs > 0 ? timeoutMs : 10000);
97 while (std::chrono::steady_clock::now() < deadline) {
99 if (http_->take(req, result) == HttpRuntime::PollStatus::Ready) {
100 const auto& c = result.completion;
101 recordSent(result.sentBytes);
102 recordCompletion(c);
103 if (c.type == NetEvType::HttpResp) {
104 status = c.status;
105 if (c.bytes) responseBody.assign(c.bytes->begin(), c.bytes->end());
106 return true;
107 }
108 if (c.type == NetEvType::Err) return false;
109 }
110 std::this_thread::sleep_for(std::chrono::milliseconds(10));
111 }
112 return false;
113}
114
115std::unique_ptr<Channel> Network::makeChannel(TcpSocket* socket) {
116 if (!socket) return nullptr;
117 auto ch = std::make_unique<Channel>(socket);
118 bindChannel(socket, ch.get());
119 return ch;
120}
121Channel* Network::newChannel(TcpSocket* socket) { return makeChannel(socket).release(); }
122
123std::unique_ptr<Session> Network::makeSession() { return std::make_unique<Session>(); }
124Session* Network::newSession() { return makeSession().release(); }
125
126std::unique_ptr<NetWriter> Network::makeWriter() { return std::make_unique<NetWriter>(); }
127NetWriter* Network::newWriter() { return makeWriter().release(); }
128
129std::unique_ptr<NetReader> Network::makeReader(std::string bytes) {
130 auto r = std::make_unique<NetReader>();
131 r->setBytes(std::move(bytes));
132 return r;
133}
134NetReader* Network::newReader(std::string bytes) { return makeReader(std::move(bytes)).release(); }
135
136std::unique_ptr<UdpLink> Network::makeUdpLink(UdpSocket* socket) {
137 if (!socket) return nullptr;
138 auto link = std::make_unique<UdpLink>(this, socket);
139 bindUdpLink(socket, link.get());
140 return link;
141}
142UdpLink* Network::newUdpLink(UdpSocket* socket) { return makeUdpLink(socket).release(); }
143
144std::unique_ptr<NetRpc> Network::makeRpc(UdpLink* link) {
145 return link ? std::make_unique<NetRpc>(link) : nullptr;
146}
148
149std::unique_ptr<NetHost> Network::makeHost() { return std::make_unique<NetHost>(this); }
150NetHost* Network::newHost() { return makeHost().release(); }
151
152void Network::bindUdpLink(UdpSocket* sock, UdpLink* link) {
153 if (sock) udpLinks_[sock] = link;
154}
155
156void Network::unbindUdpLink(UdpSocket* sock) {
157 if (sock) udpLinks_.erase(sock);
158}
159
160void Network::bindUdpHost(UdpSocket* sock, NetHost* host) {
161 if (sock) udpHosts_[sock] = host;
162}
163
164void Network::unbindUdpHost(UdpSocket* sock) {
165 if (sock) udpHosts_.erase(sock);
166}
167
168void Network::setTimeout(int ms) { http_->setTimeout(ms); }
169
170int Network::getTimeout() const { return http_->timeout(); }
171
172void Network::setVerifySsl(bool verify) { http_->setVerifySsl(verify); }
173
174bool Network::getVerifySsl() const { return http_->getVerifySsl(); }
175
176void Network::setCaLocation(std::string location) { http_->setCaLocation(std::move(location)); }
177
178void Network::recordCompletion(const NetCompletion& c) {
179 ++completions_;
180 ++telemetryRevision_;
181 if (c.bytes && (c.type == NetEvType::Data || c.type == NetEvType::HttpResp))
182 receivedBytes_ += c.bytes->size();
183 if (c.type == NetEvType::Err) ++errors_;
184 if (c.type == NetEvType::Conn && c.reason == "ok") ++connections_;
185}
186
187void Network::post(NetCompletion c) {
188 recordCompletion(c);
189 if (worker_) worker_->post(std::move(c));
190}
191
192void Network::recordSent(size_t bytes) {
193 sentBytes_ += bytes;
194 ++telemetryRevision_;
195}
196
199 result.revision = telemetryRevision_.load();
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();
205 {
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();
210 }
211 {
212 std::lock_guard<std::mutex> lock(channelMu_);
213 result.channels = channels_.size();
214 }
215 return result;
216}
217
219 sentBytes_ = receivedBytes_ = completions_ = errors_ = connections_ = 0;
220 ++telemetryRevision_;
221}
222
223void Network::drainCompletions(std::vector<NetCompletion>& out) {
224 if (worker_) worker_->drain(out);
225}
226
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_;
232 }
233}
234
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_;
240}
241
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_;
247 }
248}
249
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_;
255}
256
257void Network::bindChannel(TcpSocket* sock, Channel* ch) {
258 std::lock_guard<std::mutex> lock(channelMu_);
259 channels_[sock] = ch;
260 ++telemetryRevision_;
261}
262
263void Network::unbindChannel(TcpSocket* sock) {
264 std::lock_guard<std::mutex> lock(channelMu_);
265 if(channels_.erase(sock))++telemetryRevision_;
266}
267
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;
272}
273
274void Network::pollSockets() {
275 std::vector<TcpSocket*> tcpCopy;
276 {
277 std::lock_guard<std::mutex> lock(watchMu_);
278 tcpCopy = watchedTcp_;
279 }
280 for (TcpSocket* sock : tcpCopy) {
281 if (!sock) continue;
282 if (sock->isListening() && sock->server()) {
283 try {
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));
289 TcpSocket* raw = peer.get();
290 sock->pushAccepted(std::move(peer));
291 watchTcp(raw);
292 NetCompletion c;
293 c.type = NetEvType::Conn;
294 c.kind = NetKind::Tcp;
295 c.handle = raw;
296 c.reason = "ok";
297 c.peer = raw->getPeer();
298 post(std::move(c));
299 } catch (...) {
300 }
301 }
302 if (sock->isConnected() && sock->stream()) {
303 sock->flushSend();
304 try {
305 char buf[64 * 1024];
306 int n = sock->stream()->receiveBytes(buf, sizeof(buf));
307 if (n > 0) {
308 NetCompletion c;
309 c.type = NetEvType::Data;
310 c.kind = NetKind::Tcp;
311 c.handle = sock;
312 c.bytes = std::make_shared<std::vector<char>>(buf, buf + n);
313 c.peer = sock->getPeer();
314 post(std::move(c));
315 } else if (n == 0) {
316 NetCompletion c;
317 c.type = NetEvType::Err;
318 c.kind = NetKind::Tcp;
319 c.handle = sock;
320 c.reason = "closed";
321 post(std::move(c));
322 unwatchTcp(sock);
323 }
324 } catch (const Poco::Exception&) {
325 } catch (...) {
326 }
327 }
328 }
329 // unwatchUdp/close must wait until every borrow in this poll has retired.
330 // UDP polling only queues completions; it never invokes user callbacks.
331 std::lock_guard<std::mutex> udpLock(watchMu_);
332 for (UdpSocket* sock : watchedUdp_) {
333 if (!sock || !sock->datagram()) continue;
334 for (int i = 0; i < 64; ++i) {
335 try {
336 char buf[64 * 1024];
337 Poco::Net::SocketAddress sender;
338 int n = sock->datagram()->receiveFrom(buf, sizeof(buf), sender);
339 if (n <= 0) break; // would-block
340 NetCompletion c;
341 c.type = NetEvType::Data;
342 c.kind = NetKind::Udp;
343 c.handle = sock;
344 c.bytes = std::make_shared<std::vector<char>>(buf, buf + n);
345 c.peer = sender.toString();
346 post(std::move(c));
347 } catch (const Poco::Exception&) {
348 break;
349 } catch (...) {
350 break;
351 }
352 }
353 }
354}
355
356void Network::emitCompletion(const NetCompletion& c) {
357 auto* ev = eve::ModuleManager::getInstance<eve::platform_event::PlatformEvent>("PlatformEvent");
358 if (!ev) return;
359
362
363 std::vector<Variant> args;
364 switch (c.type) {
365 case NetEvType::Conn:
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));
369 break;
370 case NetEvType::Data: {
371 Channel* ch = channelFor(static_cast<TcpSocket*>(c.handle));
372 if (ch && c.bytes) {
373 ch->feed(*c.bytes);
374 return;
375 }
376 eve::data::ByteData* bd = nullptr;
377 if (c.bytes && !c.bytes->empty())
378 bd = new eve::data::ByteData(c.bytes->data(), c.bytes->size());
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));
383 break;
384 }
385 case NetEvType::Err: {
386 Channel* ch = channelFor(static_cast<TcpSocket*>(c.handle));
387 if (ch) {
388 args.push_back(Variant::makePtr(ch));
389 args.push_back(Variant::makeString(c.reason));
390 ev->push(std::make_unique<Message>("chclose", args));
391 }
392 args.clear();
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));
396 break;
397 }
398 case NetEvType::HttpResp: {
399 eve::data::ByteData* bd = nullptr;
400 if (c.bytes && !c.bytes->empty())
401 bd = new eve::data::ByteData(c.bytes->data(), c.bytes->size());
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));
406 break;
407 }
408 case NetEvType::ChMsg: {
409 eve::data::ByteData* bd = nullptr;
410 if (c.bytes && !c.bytes->empty())
411 bd = new eve::data::ByteData(c.bytes->data(), c.bytes->size());
412 args.push_back(Variant::makePtr(c.handle));
413 args.push_back(Variant::makeOwnedPtr(bd));
414 ev->push(std::make_unique<Message>("chmsg", args));
415 break;
416 }
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));
421 break;
422 }
423}
424
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())
430 .count();
431 for (auto& c : batch) {
432 if (c.type == NetEvType::Data && c.kind == NetKind::Udp) {
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);
437 continue;
438 }
439 auto lit = udpLinks_.find(sock);
440 if (lit != udpLinks_.end()) {
441 if (c.bytes) lit->second->onDatagram(*c.bytes, c.peer);
442 continue;
443 }
444 }
445 emitCompletion(c);
446 }
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) {
452 if (http_->prepareDelivery(result) != HttpRuntime::DeliveryStatus::Ready) continue;
453 recordSent(result.sentBytes);
454 recordCompletion(result.completion);
455 emitCompletion(result.completion);
456 }
457}
458
459void Network::expose(ssq::Table& table) {
460 auto cls = table.addClass(name, Network::create, false);
461 expose(cls);
462
463 auto tcp = table.addClass<TcpSocket>(
464 "TcpSocket", std::function<TcpSocket*()>([]() { return new TcpSocket(Network::create()); }), true);
465 tcp.addFunc("connect", &TcpSocket::connect);
466 tcp.addFunc("listen", &TcpSocket::listen);
467 tcp.addFunc("accept", &TcpSocket::accept);
468 tcp.addFunc("send", &TcpSocket::send);
469 tcp.addFunc("sendString", &TcpSocket::sendString);
470 tcp.addFunc("close", &TcpSocket::close);
471 tcp.addFunc("isConnected", &TcpSocket::isConnected);
472 tcp.addFunc("getPeer", &TcpSocket::getPeer);
473
474 auto udp = table.addClass<UdpSocket>(
475 "UdpSocket", std::function<UdpSocket*()>([]() { return new UdpSocket(Network::create()); }), true);
476 udp.addFunc("bind", &UdpSocket::bind);
477 udp.addFunc("connect", &UdpSocket::connect);
478 udp.addFunc("sendTo", &UdpSocket::sendTo);
479 udp.addFunc("sendToString", &UdpSocket::sendToString);
480 udp.addFunc("send", &UdpSocket::send);
481 udp.addFunc("sendString", &UdpSocket::sendString);
482 udp.addFunc("close", &UdpSocket::close);
483
484 auto http = table.addClass<HttpRequest>(
485 "HttpRequest",
486 std::function<HttpRequest*()>(
487 []() { return new HttpRequest(Network::create(), "GET", "http://127.0.0.1/"); }),
488 true);
489 http.addFunc("setHeader", &HttpRequest::setHeader);
490 http.addFunc("setBody", &HttpRequest::setBody);
491 http.addFunc("setBodyString", &HttpRequest::setBodyString);
492 http.addFunc("setTimeout", &HttpRequest::setTimeout);
493 http.addFunc("setVerifySsl", &HttpRequest::setVerifySsl);
494 http.addFunc("setCaLocation", &HttpRequest::setCaLocation);
495 http.addFunc("submit", &HttpRequest::submit);
496
497 auto ch = table.addClass<Channel>(
498 "Channel", std::function<Channel*()>([]() { return new Channel(nullptr); }), true);
499 ch.addFunc("sendMsg", &Channel::sendMsg);
500 ch.addFunc("sendMsgString", &Channel::sendMsgString);
501 ch.addFunc("getSocket", &Channel::getSocket);
502
503 auto sess = table.addClass<Session>(
504 "Session", std::function<Session*()>([]() { return new Session(); }), true);
505 sess.addFunc("add", &Session::add);
506 sess.addFunc("get", &Session::get);
507 sess.addFunc("remove", &Session::remove);
508 sess.addFunc("closeAll", &Session::closeAll);
509
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)); });
520 writer.addFunc("writeF32", &NetWriter::writeF32);
521 writer.addFunc("writeF64", &NetWriter::writeF64);
524 writer.addFunc("writeBytes", [](NetWriter* w, eve::data::ByteData* d) {
525 if (d) w->writeBytes(d->getData(), d->getSize());
526 });
528 writer.addFunc("size", [](NetWriter* w) { return static_cast<int64_t>(w->size()); });
529
530 auto reader = table.addClass<NetReader>(
531 "NetReader", std::function<NetReader*()>([]() { return new NetReader(); }), true);
532 reader.addFunc("init", [](NetReader* r, eve::data::ByteData* d) {
533 return d ? r->init(d->getData(), d->getSize()) : false;
534 });
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()); });
544 reader.addFunc("f32", &NetReader::f32);
545 reader.addFunc("f64", &NetReader::f64);
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());
551 });
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()); });
555
556 auto link = table.addClass<UdpLink>(
557 "UdpLink",
558 std::function<UdpLink*()>([]() { return new UdpLink(nullptr, nullptr); }), true);
559 link.addFunc("setRemote", &UdpLink::setRemote);
560 link.addFunc("setRemoteString", &UdpLink::setRemoteString);
561 link.addFunc("sendReliable", [](UdpLink* l, int64_t ch, const std::string& s) {
562 l->sendString(UdpLink::MsgType::Reliable, static_cast<uint8_t>(ch), s);
563 });
564 link.addFunc("sendUnreliable", [](UdpLink* l, int64_t ch, const std::string& s) {
565 l->sendString(UdpLink::MsgType::Unreliable, static_cast<uint8_t>(ch), s);
566 });
567 link.addFunc("sendOrdered", [](UdpLink* l, int64_t ch, const std::string& s) {
568 l->sendString(UdpLink::MsgType::UnreliableOrdered, static_cast<uint8_t>(ch), s);
569 });
570 link.addFunc("onMessage", [](UdpLink* l, ssq::Object fn) {
571 if (!l) return;
572 l->setMessageHandler(
573 [fn](UdpLink::MsgType, uint8_t ch, const char* d, size_t n) {
574 callScript2(fn, ch, std::string(d, n));
575 });
576 });
577 link.addFunc("setLossRate", &UdpLink::setLossRate);
578 link.addFunc("setTimeoutMs", &UdpLink::setTimeoutMs);
579 link.addFunc("isAlive", [](UdpLink* l) { return l && l->isAlive(); });
580 link.addFunc("peer", &UdpLink::peer);
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()); });
586
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,
590 bool reliable) {
591 r->callString(static_cast<uint16_t>(msgId), payload, reliable);
592 });
593 rpc.addFunc("registerRpc", [](NetRpc* r, int64_t msgId, ssq::Object fn) {
594 r->registerScript(static_cast<uint16_t>(msgId), fn);
595 });
596
597 auto host = table.addClass<NetHost>(
598 "NetHost", std::function<NetHost*()>([]() { return new NetHost(nullptr); }), true);
599 host.addFunc("start", &NetHost::start);
600 host.addFunc("onMessage", [](NetHost* h, ssq::Object fn) {
601 if (!h) return;
602 h->setMessageHandler(
603 [fn](uint32_t peerId, UdpLink::MsgType, uint8_t ch, const char* d, size_t n) {
604 callScript3(fn, peerId, ch, std::string(d, n));
605 });
606 });
607 host.addFunc("onPeerConnected", [](NetHost* h, ssq::Object fn) {
608 if (!h) return;
609 h->setPeerConnectedHandler([fn](uint32_t id) { callScript2(fn, id, ""); });
610 });
611 host.addFunc("onPeerDisconnected", [](NetHost* h, ssq::Object fn) {
612 if (!h) return;
613 h->setPeerDisconnectedHandler([fn](uint32_t id) { callScript2(fn, id, ""); });
614 });
615 host.addFunc("sendReliable", [](NetHost* h, int64_t peerId, int64_t ch,
616 const std::string& s) {
617 h->sendStringTo(static_cast<uint32_t>(peerId), UdpLink::MsgType::Reliable,
618 static_cast<uint8_t>(ch), s);
619 });
620 host.addFunc("sendUnreliable", [](NetHost* h, int64_t peerId, int64_t ch,
621 const std::string& s) {
622 h->sendStringTo(static_cast<uint32_t>(peerId), UdpLink::MsgType::Unreliable,
623 static_cast<uint8_t>(ch), s);
624 });
625 host.addFunc("sendOrdered", [](NetHost* h, int64_t peerId, int64_t ch,
626 const std::string& s) {
627 h->sendStringTo(static_cast<uint32_t>(peerId), UdpLink::MsgType::UnreliableOrdered,
628 static_cast<uint8_t>(ch), s);
629 });
630 host.addFunc("link", &NetHost::linkByPeerId);
631 host.addFunc("peerCount", [](NetHost* h) { return static_cast<int64_t>(h->peerCount()); });
632 host.addFunc("setLossRate", &NetHost::setLossRate);
633 host.addFunc("setTimeoutMs", &NetHost::setTimeoutMs);
634}
635
636void Network::expose(ssq::Class& cls) {
637 cls.addFunc("getName", &Network::getName);
638 cls.addFunc("newTcp", &Network::newTcp);
639 cls.addFunc("newUdp", &Network::newUdp);
640 cls.addFunc("newHttp", &Network::newHttp);
641 cls.addFunc("newChannel", &Network::newChannel);
642 cls.addFunc("newSession", &Network::newSession);
643 cls.addFunc("newWriter", &Network::newWriter);
644 cls.addFunc("newReader", &Network::newReader);
645 cls.addFunc("newUdpLink", &Network::newUdpLink);
646 cls.addFunc("newRpc", &Network::newRpc);
647 cls.addFunc("newHost", &Network::newHost);
648 cls.addFunc("pump", &Network::pump);
649 cls.addFunc("setTimeout", &Network::setTimeout);
650 cls.addFunc("setVerifySsl", &Network::setVerifySsl);
651 cls.addFunc("setCaLocation", &Network::setCaLocation);
652}
653
654} // namespace eve::network
Value::Object payload
float w
Definition AnimClip.cpp:738
const std::string & s
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
double raw
std::uint16_t method
wgpu::PopErrorScopeStatus status
glm::vec3 n
Definition Grass.cpp:63
double r
float v
std::int32_t c
int h
PhysicsJointLink link
std::chrono::steady_clock::time_point deadline
Poco::JSON::Object::Ptr result
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
float f
bool hit
std::string body
float d
ScriptStructure out
The single Squirrel projection for common Result, Status and Value.
UIHostHandle host
virtual std::string getName() const =0
Returns the name.
In-memory byte buffer implementing eve::Data (ref-counted).
Definition ByteData.h:13
Length-prefixed (big-endian uint32) message framing over a TcpSocket. sendMsg() writes one framed mes...
Definition Channel.h:23
bool sendMsg(eve::data::ByteData *data)
Sends one framed message.
Definition Channel.cpp:38
TcpSocket * getSocket() const
The underlying TCP socket, or nullptr.
Definition Channel.h:39
bool sendMsgString(std::string s)
Sends a string payload as one framed message (empty strings are rejected).
Definition Channel.cpp:59
Asynchronous HTTP request (Poco-based). Configure headers/body, call submit(), then receive the respo...
Definition HttpRequest.h:33
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.
Definition NetHost.h:25
void setLossRate(float rate)
Sets the loss rate.
Definition NetHost.cpp:41
bool start(uint16_t port)
Starts .
Definition NetHost.cpp:29
void setTimeoutMs(int ms)
Sets the timeout ms.
Definition NetHost.cpp:46
UdpLink * linkByPeerId(uint32_t peerId) const
Link by peer id.
Definition NetHost.cpp:81
EVENGINE_API_PLATFORM public API.
Definition NetStream.h:71
bool ok() const
Ok.
Definition NetStream.h:118
std::string str()
Str.
Definition NetHost.cpp:377
EVENGINE_API_PLATFORM public API.
Definition NetRpc.h:26
EVENGINE_API_PLATFORM public API.
Definition NetStream.h:20
std::string toString() const
To string.
Definition NetStream.h:59
void writeBool(bool v)
Writes bool.
Definition NetHost.cpp:281
void writeF32(float v)
Writes f 32.
Definition NetHost.cpp:267
void writeString(const std::string &s)
Writes string.
Definition NetHost.cpp:283
void writeF64(double v)
Writes f 64.
Definition NetHost.cpp:274
Network module: TCP/UDP/HTTP factories, background worker, and completion event plumbing....
Definition Network.h:39
NetHost * newHost()
Script adapter: creates a caller-owned UDP host.
Definition Network.cpp:150
std::unique_ptr< TcpSocket > makeTcp()
Creates an owning TCP socket handle for C++ callers.
Definition Network.cpp:71
NetReader * newReader(std::string bytes)
Script adapter: creates a caller-owned reader.
Definition Network.cpp:134
std::unique_ptr< NetRpc > makeRpc(UdpLink *link)
Creates an owning RPC handle, or null for a null link.
Definition Network.cpp:144
bool getVerifySsl() const
Returns the verify ssl.
Definition Network.cpp:174
std::unique_ptr< NetReader > makeReader(std::string bytes)
Creates an owning streaming reader handle.
Definition Network.cpp:129
friend class HttpRequest
Definition Network.h:125
void setTimeout(int ms)
Default socket/HTTP timeout in milliseconds.
Definition Network.cpp:168
void setCaLocation(std::string location)
Sets an owning UTF-8 CA file or hashed CA directory for future HTTPS requests. Empty selects system/d...
Definition Network.cpp:176
Session * newSession()
Script adapter: creates a caller-owned session.
Definition Network.cpp:124
void resetTelemetry()
Reset cumulative telemetry counters without affecting live sockets.
Definition Network.cpp:218
std::unique_ptr< Session > makeSession()
Creates an owning session handle.
Definition Network.cpp:123
UdpLink * newUdpLink(UdpSocket *socket)
Script adapter: creates a caller-owned UDP link.
Definition Network.cpp:142
std::unique_ptr< NetWriter > makeWriter()
Creates an owning streaming writer handle.
Definition Network.cpp:126
std::unique_ptr< UdpSocket > makeUdp()
Creates an owning UDP socket handle for C++ callers.
Definition Network.cpp:74
void setVerifySsl(bool verify)
Whether TLS peer certificates are verified (default true).
Definition Network.cpp:172
std::unique_ptr< Channel > makeChannel(TcpSocket *socket)
Creates an owning channel handle, or null for a null socket.
Definition Network.cpp:115
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...
Definition Network.cpp:84
HttpRequest * newHttp(std::string method, std::string url)
Script adapter: creates a caller-owned HTTP request.
Definition Network.cpp:80
std::unique_ptr< HttpRequest > makeHttp(std::string method, std::string url)
Creates an owning HTTP request handle for C++ callers.
Definition Network.cpp:77
friend class NetHost
Definition Network.h:126
std::unique_ptr< NetHost > makeHost()
Creates an owning UDP host handle.
Definition Network.cpp:149
int getTimeout() const
Returns the timeout.
Definition Network.cpp:170
~Network() override
Cancels HTTP completions and joins background I/O before destruction. @cost May wait for in-flight so...
Definition Network.cpp:64
friend class TcpSocket
Definition Network.h:128
friend class Channel
Definition Network.h:124
NetRpc * newRpc(UdpLink *link)
Script adapter: creates a caller-owned RPC client.
Definition Network.cpp:147
void pump()
Drains worker completions and emits them as events; call per frame.
Definition Network.cpp:425
NetWriter * newWriter()
Script adapter: creates a caller-owned writer.
Definition Network.cpp:127
UdpSocket * newUdp()
Script adapter: creates a caller-owned UDP socket.
Definition Network.cpp:75
friend class UdpSocket
Definition Network.h:129
TcpSocket * newTcp()
Script adapter: creates a caller-owned TCP socket.
Definition Network.cpp:72
std::unique_ptr< UdpLink > makeUdpLink(UdpSocket *socket)
Creates an owning UDP link handle, or null for a null socket.
Definition Network.cpp:136
NetTelemetrySnapshot telemetrySnapshot() const
Return a thread-safe copied telemetry snapshot for diagnostics tools.
Definition Network.cpp:197
Channel * newChannel(TcpSocket *socket)
Script adapter: creates a caller-owned channel.
Definition Network.cpp:121
Named collection of Channels (a "session"). Lookup by name, close all. Does not own the channels; the...
Definition Session.h:16
void remove(std::string name)
Removes a channel from the session (does not delete it).
Definition Session.cpp:20
void add(std::string name, Channel *ch)
Registers a channel under a name (replaces an existing entry).
Definition Session.cpp:11
void closeAll()
Closes every channel in the session.
Definition Session.cpp:24
Channel * get(std::string name)
Finds a channel by name, or nullptr.
Definition Session.cpp:15
TCP socket backed by Poco::Net; supports both client (connect) and server (listen/accept) roles....
Definition TcpSocket.h:30
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.
Definition TcpSocket.cpp:56
bool send(eve::data::ByteData *data)
Sends a framed byte payload; true when queued/accepted.
UDP socket backed by Poco::Net; supports connect/bind and datagram send. @ownership The caller owns t...
Definition UdpSocket.h:30
bool sendTo(eve::data::ByteData *data, std::string host, uint16_t port)
Sends a datagram to an explicit host:port.
Definition UdpSocket.cpp:87
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.
Definition UdpSocket.cpp:30
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()).
Definition UdpSocket.cpp:57
bool send(eve::data::ByteData *data)
Sends a datagram to the connected peer.
A named event carrying an ordered list of Variant payloads. Pushed messages are heap-allocated; the q...
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
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
NetCompletion completion
Definition HttpRuntime.h:31
One asynchronous network result/event. handle points at the originating TcpSocket/UdpSocket/HttpReque...
Definition NetTypes.h:33
Copied aggregate counters for editor/profiler network inspection.
Definition NetTypes.h:44