43#if !defined(_REQUESTGATEWAY_H_)
44#define _REQUESTGATEWAY_H_
77 "{\"id\":%llu, \"port\":%u, \"source\":\"%u.%u.%u.%u:%u\", \"connectiontype\":\"%s\", \"messagetype\":\"%s\", "
78 "\"requesttype\":\"%s\", \"longrequest\": \"%s\", \"status\": \"%s\", \"request\": \"%s\", \"output\": \"%s\", "
79 "\"executorid\":%llu, \"clientid\":%llu, \"accountid\":%u, "
80 "\"requestsize\":%u, \"replysize\":%u, "
81 "\"requesttime\": \"%s\", \"duration\": \"%.3f\", \"queuetime\": \"%.3f\", \"processtime\": \"%.3f\"}\n",
83 ((
conType == 1) ?
"Client" : (
conType == 2) ?
"Web" :
"Websocket"),
147 static bool UnitTest(uint16
port, uint32 executorCount, uint32 gatewayCount, uint32 clientCount, uint32 webCount, uint32 webSocketCount,
double sendfreq, int32 reconnect, uint32 payload, uint32 processTime, uint32 runtime);
160 bool init(
const char* sslCertPath = NULL,
const char* sslKeyPath = NULL);
193 bool addPort(uint16
port, uint8 encryption,
bool enableHTTP =
false, uint32 timeout = 3000);
199 bool addAuthUser(
const char* user,
const char* password);
236 uint64
getBestExecutorID(std::string requestString, uint32 reqSize,
bool& isLongReq);
268 const char* requestPath,
Connection/channel management layer: multi-protocol listeners, typed dispatch, HTTP client — and the ...
Request-system client side: RequestReply futures, RequestQueue, gateway connection records and the Re...
Request-system worker side: RequestExecutor pulls requests from a RequestGateway, processes them and ...
Thread-safe running statistics over a sliding window of samples.
#define THREAD_FUNCTION_CALL
#define GETIPADDRESSQUADPORT(a)
uint64 executorID
Executor that processed the request.
uint64 endTime
Reply completion time (ms epoch).
uint32 requestSize
Request payload size in bytes.
uint16 port
Gateway port the call arrived on.
uint64 queueTime
Time spent queued before dispatch (µs).
uint64 processTime
Time spent processing in the executor (µs).
uint8 conType
Ingress type — 1: client 2: web 3: websocket.
CallLogEntry(uint64 id=0)
uint8 messageType
Wire format — 1: message 2: http 3: https.
uint64 source
Caller endpoint packed as uint64.
uint32 replySize
Reply payload size in bytes.
std::string output
Output/diagnostic note.
std::string agent
Caller's User-Agent (web ingress).
uint64 clientID
Client connection id.
uint64 startTime
Request arrival time (ms epoch).
uint8 requestType
HTTP_* method id (for web ingress).
std::string requestPath
Request name/URI.
uint32 accountID
Authenticated account id (0 if anonymous).
bool longRequest
Whether the request was classified long.
std::string status
Outcome status text.
The central Psyclone data container: a self-contained binary message with typed, named user entries.
A parsed or generated HTTP request (also used for WebSocket upgrade handshakes).
Circular-buffer moving statistics: query average, sum and per-second throughput over recent time wind...
One logical network interface: a group of listeners/connections with shared dispatch.
Central owner of all channels, listeners and connections in a process.
uint32 longReqLimit
Concurrent long-request cap per executor.
bool setResponseType(const char *type)
Choose the reply serialisation ("xml" or "json").
std::map< std::string, uint64 > httpAuth
Basic-auth users (user -> credential hash).
std::map< uint64, RequestReply * > requestMap
In-flight requests by gateway ref id.
bool addAuthUser(const char *user, const char *password)
Add a basic-auth user for the web interface/APIs.
bool distributeDeadExecutorRequests(std::list< RequestReply * > &shortQueue, std::list< RequestReply * > &longQueue)
Requeue a dead executor's outstanding requests onto surviving executors.
friend THREAD_RET THREAD_FUNCTION_CALL RequestGatewayClientRun(THREAD_ARG arg)
Thread entry point for the gateway's client-side loop.
uint64 systemStartTime
Gateway start time (ms epoch), for uptime reporting.
uint64 execSentCount
Messages sent to executors.
bool receiveWebsocketData(WebsocketData *wsData, NetworkChannel *channel, uint64 conid)
NetworkReceiver hook: WebSocket ingress carrying request payloads.
uint32 executorHeartbeatTimeout
Silence threshold before an executor is declared dead (ms).
std::map< uint64, RequestConnection > webSockets
Connected WebSocket clients by id.
bool receiveMessage(DataMessage *msg, NetworkChannel *channel, uint64 conid)
NetworkReceiver hook: binary requests/replies/heartbeats from clients and executors.
NetworkChannel * channel
Channel carrying all gateway traffic.
virtual ~RequestGateway()
uint64 callLogCount
Total calls logged since start.
utils::Mutex callLogMutex
Guards the call log.
bool callInternalAPI(const char *apiName, HTTPRequest *req, NetworkChannel *channel, uint64 conid)
Handle a management/API call on the internal API label.
std::map< uint64, RequestConnection > executors
Connected executors by id.
uint64 lastRefID
Last issued gateway reference id.
std::string indexFilename
Default index file name.
std::string externalAPITitle
URI label of the external (public) API.
bool setCacheFiles(bool cache)
Enable/disable HTTP caching headers for served files.
bool setMaxExecutorRequestTimeout(uint32 timeout)
Set the maximum time a request may sit with an executor before being failed/retried.
uint32 id
This gateway's id.
bool setExecutorHeartbeatTimeout(uint32 timeout)
Set how long an executor may go silent before being declared dead (its queue is then redistributed).
std::string webServerName
Server header name of the built-in web server.
uint16 port
Primary listening port.
utils::WaitQueue< RequestReply * > execQ
Requests awaiting executor dispatch.
uint32 maxRequestProcessingSize
Backpressure: max requests dispatched concurrently.
std::vector< std::string > longReqNames
Request names classified as long.
bool receiveHTTPRequest(HTTPRequest *req, NetworkChannel *channel, uint64 conid)
NetworkReceiver hook: web ingress — serves files, APIs, or converts the request into an internal Data...
std::string rootdir
Document root for file serving.
bool callExternalAPI(const char *apiName, HTTPRequest *req, NetworkChannel *channel, uint64 conid)
Handle a public API call on the external API label.
std::map< uint64, RequestConnection > webClients
Connected HTTP clients by id.
bool addToCallLog(uint64 id, uint8 conType, uint8 messageType, bool longRequest, uint64 source, uint16 port, uint64 executorID, uint64 clientID, uint64 startTime, uint64 endTime, uint64 queueTime, uint64 processTime, uint8 requestType, uint32 requestSize, uint32 replySize, const char *status, const char *requestPath, const char *agent, const char *output)
Append one completed call to the rolling call log (trimmed to callLogMax).
uint64 execReceivedCount
Messages received from executors.
bool setQueuingParameters(uint32 maxRequestQueueSize, uint32 maxRequestProcessingSize, uint32 priorityThreshold)
Tune queuing/backpressure behaviour.
bool sslSupport
True when an SSL certificate was configured.
uint64 clientReceivedCount
Messages received from clients.
std::string versionString
Version shown in status pages.
MovingAverage shortAvgStats
Rolling latency stats for short requests.
bool addGateway(uint32 id, std::string addr, uint16 port)
Register a peer gateway (multi-gateway federation).
uint32 threadIDClient
Client-side worker thread id.
MovingAverage longAvgStats
Rolling latency stats for long requests.
bool cacheFiles
Send caching headers for served files.
uint32 maxRequestQueueSize
Backpressure: max queued requests before TOOBUSY.
bool setLongRequestLimit(uint32 limit)
Cap concurrent long requests per executor.
std::string internalAPITitle
URI label of the internal (management) API.
std::map< uint64, RequestConnection > clients
Connected binary clients by id.
bool setExternalAPILabel(const char *label)
Set the URI label under which the external (public) API is exposed.
uint64 getBestExecutorID(std::string requestString, uint32 reqSize, bool &isLongReq)
Pick the executor to receive a request — the core load-balancing decision, based on reported queue si...
NetworkManager * manager
Owned network stack (listeners + connections).
bool addPort(uint16 port, uint8 encryption, bool enableHTTP=false, uint32 timeout=3000)
Open a listening port for clients/executors (call before init()).
uint32 maxExecutorRequestTimeoutMS
Max time a request may sit with an executor (ms).
bool sendRestartToExecutor(uint64 id)
Ask an executor to restart itself (sent when it misbehaves).
bool setInternalAPILabel(const char *label)
Set the URI label under which the internal (management) API is exposed.
utils::WaitQueuePointer< DataMessage * > replyQ
Replies awaiting client routing.
std::list< CallLogEntry * > callLog
Rolling log of completed calls (owned).
bool setWebServerInfo(const char *name, const char *rootdir, const char *indexfile)
Configure the built-in file web server.
RequestGateway(uint32 id, const char *version=NULL)
bool runClient()
Client-side worker loop: route replies back to callers, expire timed-out requests.
friend THREAD_RET THREAD_FUNCTION_CALL RequestGatewayExecRun(THREAD_ARG arg)
Thread entry point for the gateway's executor-side loop.
bool runExec()
Executor-side worker loop: dispatch queued requests, watch heartbeats, redistribute dead executors' w...
utils::Mutex mutex
Guards shared gateway state.
uint32 priorityThreshold
Queue length above which priority ordering applies.
static bool UnitTest(uint16 port, uint32 executorCount, uint32 gatewayCount, uint32 clientCount, uint32 webCount, uint32 webSocketCount, double sendfreq, int32 reconnect, uint32 payload, uint32 processTime, uint32 runtime)
End-to-end stress test spinning up a gateway plus the given numbers of executors, extra gateways and ...
bool addToRequestQueue(DataMessage *msg, uint64 origin, uint64 conID, uint64 clientRef)
Wrap an incoming message in a RequestReply and enqueue it for dispatch.
bool addRequestReplyToRequestQueue(RequestReply *reply)
Enqueue an already-wrapped request (e.g.
uint32 callLogMax
Max entries kept in callLog.
bool init(const char *sslCertPath=NULL, const char *sslKeyPath=NULL)
Start the gateway threads and network stack.
bool receiveNetworkEvent(NetworkEvent *evt, NetworkChannel *channel, uint64 conid)
NetworkReceiver hook: connect/disconnect events for clients and executors.
bool replyXML
Reply in XML (true) or JSON (false).
bool replyToClient(DataMessage *msg)
Route a reply message back to the client that issued the request.
uint64 clientSentCount
Messages sent to clients.
Future/handle for one in-flight request: holds the request message, the eventual reply,...
Runnable()
Initialise flags: not running, allowed to continue.
One WebSocket frame/message (RFC 6455): parsing, generation and control frames.
Recursive mutual-exclusion lock, optionally named for cross-process use.
Thread-safe FIFO queue with blocking waits, the workhorse producer/consumer channel in CMSDK.
WaitQueue specialization for owned heap pointers: clear()/destructor delete remaining entries.
std::string PrintTimeString(uint64 t, bool local=true, bool us=true, bool ms=true)
THREAD_RET THREAD_FUNCTION_CALL RequestGatewayExecRun(THREAD_ARG arg)
Thread entry point for the gateway's executor-side loop.
THREAD_RET THREAD_FUNCTION_CALL RequestGatewayClientRun(THREAD_ARG arg)
Thread entry point for the gateway's client-side loop.
std::string StringFormat(const char *format,...)
printf into a std::string.
static char HTTP_Type[][8]
HTTP method name strings, indexed by the HTTP_* method ids (index 0 unused).
Notification of a connection lifecycle change (connect, disconnect, buffer state.....