Skip to content

Commit 1e134ac

Browse files
committed
Add App::addChildApp for easy load balancing alternative
1 parent 7fa38c6 commit 1e134ac

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/App.h

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,29 @@ struct TemplatedApp {
576576
return std::move(static_cast<BuilderPatternReturnType &&>(*this));
577577
}
578578

579+
BuilderPatternReturnType &&addChildApp(BuilderPatternReturnType *app) {
580+
/* Add this app to httpContextData list over child apps and set onPreOpen */
581+
httpContext->getSocketContextData()->childApps.push_back((void *) app);
582+
583+
httpContext->onPreOpen([](struct us_socket_context_t *context, LIBUS_SOCKET_DESCRIPTOR fd) -> LIBUS_SOCKET_DESCRIPTOR {
584+
HttpContext<SSL> *httpContext = (HttpContext<SSL> *) context;
585+
586+
int &roundRobin = &httpContext->getSocketContextData()->roundRobin;
587+
BuilderPatternReturnType *receivingApp = (BuilderPatternReturnType *) httpContext->getSocketContextData()->childApps[roundRobin];
588+
589+
receivingApp->getLoop()->defer([fd, receivingApp]() {
590+
receivingApp->adoptSocket(fd);
591+
});
592+
593+
if (++roundRobin == httpContext->getSocketContextData()->childApps.size()) {
594+
roundRobin = 0;
595+
}
596+
597+
return fd + 1;
598+
});
599+
return std::move(static_cast<BuilderPatternReturnType &&>(*this));
600+
}
601+
579602
/* adopt an externally accepted socket */
580603
BuilderPatternReturnType &&adoptSocket(LIBUS_SOCKET_DESCRIPTOR accepted_fd) {
581604
httpContext->adoptAcceptedSocket(accepted_fd);

src/HttpContextData.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,10 @@ struct alignas(16) HttpContextData {
4949
HttpRouter<RouterData> router;
5050
void *upgradedWebSocket = nullptr;
5151
bool isParsingHttp = false;
52+
53+
/* If we are main acceptor, distribute to these apps */
54+
std::vector<void *> childApps;
55+
unsigned int roundRobin = 0;
5256
};
5357

5458
}

0 commit comments

Comments
 (0)