Skip to content

Commit

Permalink
Add App::addChildApp for easy load balancing alternative
Browse files Browse the repository at this point in the history
  • Loading branch information
uNetworkingAB committed Aug 23, 2024
1 parent 7fa38c6 commit 1e134ac
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/App.h
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,29 @@ struct TemplatedApp {
return std::move(static_cast<BuilderPatternReturnType &&>(*this));
}

BuilderPatternReturnType &&addChildApp(BuilderPatternReturnType *app) {
/* Add this app to httpContextData list over child apps and set onPreOpen */
httpContext->getSocketContextData()->childApps.push_back((void *) app);

httpContext->onPreOpen([](struct us_socket_context_t *context, LIBUS_SOCKET_DESCRIPTOR fd) -> LIBUS_SOCKET_DESCRIPTOR {
HttpContext<SSL> *httpContext = (HttpContext<SSL> *) context;

int &roundRobin = &httpContext->getSocketContextData()->roundRobin;
BuilderPatternReturnType *receivingApp = (BuilderPatternReturnType *) httpContext->getSocketContextData()->childApps[roundRobin];

receivingApp->getLoop()->defer([fd, receivingApp]() {
receivingApp->adoptSocket(fd);
});

if (++roundRobin == httpContext->getSocketContextData()->childApps.size()) {
roundRobin = 0;
}

return fd + 1;
});
return std::move(static_cast<BuilderPatternReturnType &&>(*this));
}

/* adopt an externally accepted socket */
BuilderPatternReturnType &&adoptSocket(LIBUS_SOCKET_DESCRIPTOR accepted_fd) {
httpContext->adoptAcceptedSocket(accepted_fd);
Expand Down
4 changes: 4 additions & 0 deletions src/HttpContextData.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ struct alignas(16) HttpContextData {
HttpRouter<RouterData> router;
void *upgradedWebSocket = nullptr;
bool isParsingHttp = false;

/* If we are main acceptor, distribute to these apps */
std::vector<void *> childApps;
unsigned int roundRobin = 0;
};

}
Expand Down

0 comments on commit 1e134ac

Please sign in to comment.