CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
cmlabs::RequestClient Class Reference

Application-facing client of the request system: posts DataMessage requests to one or more RequestGateways and delivers replies. More...

#include <RequestClient.h>

Inheritance diagram for cmlabs::RequestClient:
[legend]
Collaboration diagram for cmlabs::RequestClient:
[legend]

Public Member Functions

 RequestClient ()
virtual ~RequestClient ()
bool isConnected ()
bool waitForConnection (uint32 timeoutMS)
 Block until a gateway connection is established.
bool reconnect ()
 Force reconnection of gateway links.
bool addGateway (uint32 id, std::string addr, uint16 port, uint8 encryption=NOENC)
 Register a gateway to connect to (may be called several times for redundancy).
RequestReplypostRequest (DataMessage *msg)
 Post a request asynchronously.
bool postRequest (DataMessage *msg, RequestCallbackFunction callback, uint32 timeoutMS)
 Post a request with a completion callback (fire-and-forget style).
bool finishRequest (RequestReply *reply)
 Release a RequestReply obtained from postRequest() back to the client's pool.
bool receiveNetworkEvent (NetworkEvent *evt, NetworkChannel *channel, uint64 conid)
 NetworkReceiver hook: gateway connect/disconnect events (drives reconnection).
bool receiveMessage (DataMessage *msg, NetworkChannel *channel, uint64 conid)
 NetworkReceiver hook: reply messages from gateways, matched to pending requests.
bool receiveHTTPReply (HTTPReply *reply, HTTPRequest *req, NetworkChannel *channel, uint64 conid)
 NetworkReceiver hook: HTTP replies (when talking to a gateway over HTTP).
Public Member Functions inherited from cmlabs::Runnable
 Runnable ()
 Initialise flags: not running, allowed to continue.
virtual ~Runnable ()
 Destructor requests a stop (with the default timeout) before destruction proceeds.
virtual bool stop (uint32 timeout=200)
 Ask the worker loop to finish and wait for it to do so.
Public Member Functions inherited from cmlabs::NetworkReceiver
 NetworkReceiver ()
virtual bool receiveHTTPRequest (HTTPRequest *req, NetworkChannel *channel, uint64 conid)
 An HTTP request arrived on a server connection.
virtual bool receiveTelnetLine (TelnetLine *line, NetworkChannel *channel, uint64 conid)
 A Telnet line arrived.
virtual bool receiveWebsocketData (WebsocketData *wsData, NetworkChannel *channel, uint64 conid)
 A WebSocket message arrived.

Static Public Member Functions

static bool TestServerLogin (const char *address, uint16 port, const char *username, const char *password, const char *reqAfterLogin)
 Manual test: log in to a request server and issue a request.
static std::string SendRequestAndWaitForJSON (RequestClient *client, DataMessage *msg, int timeoutMS)
 Convenience: post msg on client, wait, and return the reply's JSON text.
static DataMessageSendRequestAndWaitForReply (RequestClient *client, DataMessage *msg, int timeoutMS)
 Convenience: post msg, wait, and return the reply message.
static RequestReplySendRequestAndWaitForReplyObject (RequestClient *client, DataMessage *msg, int timeoutMS)
 Convenience: post msg, wait, and return the whole RequestReply object.
static std::string GetJSONReplyParameter (const char *json, const char *name)
 Extract a named top-level string value from a JSON reply.
static DataMessageCreateRequestMessage (uint8 operation, const char *req, const char *key1=NULL, const char *val1=NULL, const char *key2=NULL, const char *val2=NULL, const char *key3=NULL, const char *val3=NULL, const char *key4=NULL, const char *val4=NULL, const char *key5=NULL, const char *val5=NULL, const char *key6=NULL, const char *val6=NULL, const char *key7=NULL, const char *val7=NULL, const char *key8=NULL, const char *val8=NULL, const char *key9=NULL, const char *val9=NULL, const char *key10=NULL, const char *val10=NULL, const char *key11=NULL, const char *val11=NULL, const char *key12=NULL, const char *val12=NULL, const char *key13=NULL, const char *val13=NULL, const char *key14=NULL, const char *val14=NULL, const char *key15=NULL, const char *val15=NULL, const char *key16=NULL, const char *val16=NULL, const char *key17=NULL, const char *val17=NULL, const char *key18=NULL, const char *val18=NULL, const char *key19=NULL, const char *val19=NULL, const char *key20=NULL, const char *val20=NULL)
 Build a request DataMessage from an operation, request name and up to 20 key/value string pairs (NULL-terminated usage; pass pairs only as needed).

Protected Member Functions

bool sendRequest (RequestReply *reply)
 Serialise and send one request to the best available gateway.
bool run ()
 Worker loop: connection upkeep, outgoing queue, timeouts.
bool sendMessageToGateway (DataMessage *msg, RequestGatewayConnection &con)
 Send a message on a specific gateway link.
uint32 sendStatusNow ()
 Send a status/heartbeat message to all gateways.

Protected Attributes

NetworkManagermanager
 Owned network stack for gateway links.
NetworkChannelchannel
 Channel carrying the gateway connections.
std::list< RequestGatewayConnectionconnections
 Configured gateways and their state.
utils::Mutex mutex
 Guards request bookkeeping.
utils::Mutex conMutex
 Guards ::connections.
utils::WaitQueuePointer< RequestReply * > outQ
 Outgoing requests awaiting dispatch.
std::map< uint64, RequestReply * > requestMap
 In-flight requests by client reference id.
uint32 threadID
 Worker thread id.
uint64 lastRefID
 Last issued client reference id.
uint64 sentCount
 Total requests sent.
uint64 receivedCount
 Total replies received.
MovingAverage avgStats
 Rolling round-trip statistics.
Protected Attributes inherited from cmlabs::Runnable
uint32 threadID
 ThreadManager slot ID of the worker thread (0 until known).
bool shouldContinue
 Loop-continuation flag; cleared by stop().
bool isRunning
 Set by the worker while its loop is active.

Friends

THREAD_RET THREAD_FUNCTION_CALL RequestClientRun (THREAD_ARG arg)
 Thread entry point for the RequestClient worker loop.

Detailed Description

Application-facing client of the request system: posts DataMessage requests to one or more RequestGateways and delivers replies.

Owns its own NetworkManager/NetworkChannel and a worker thread that maintains gateway connections (with automatic reconnection and periodic status messages), drains the outgoing queue and matches incoming replies to pending RequestReply objects via reference ids. See the file header for a full round-trip example.

Ownership
RequestReply objects returned by postRequest() remain owned by the client; release them with finishRequest(). DataMessages passed to postRequest() are taken over by the reply object.
Thread-safety
All public methods may be called from any thread.

Definition at line 357 of file RequestClient.h.

Constructor & Destructor Documentation

◆ RequestClient()

◆ ~RequestClient()

cmlabs::RequestClient::~RequestClient ( )
virtual

Definition at line 304 of file RequestClient.cpp.

References conMutex, manager, mutex, requestMap, and cmlabs::Runnable::stop().

Member Function Documentation

◆ addGateway()

◆ CreateRequestMessage()

DataMessage * cmlabs::RequestClient::CreateRequestMessage ( uint8 operation,
const char * req,
const char * key1 = NULL,
const char * val1 = NULL,
const char * key2 = NULL,
const char * val2 = NULL,
const char * key3 = NULL,
const char * val3 = NULL,
const char * key4 = NULL,
const char * val4 = NULL,
const char * key5 = NULL,
const char * val5 = NULL,
const char * key6 = NULL,
const char * val6 = NULL,
const char * key7 = NULL,
const char * val7 = NULL,
const char * key8 = NULL,
const char * val8 = NULL,
const char * key9 = NULL,
const char * val9 = NULL,
const char * key10 = NULL,
const char * val10 = NULL,
const char * key11 = NULL,
const char * val11 = NULL,
const char * key12 = NULL,
const char * val12 = NULL,
const char * key13 = NULL,
const char * val13 = NULL,
const char * key14 = NULL,
const char * val14 = NULL,
const char * key15 = NULL,
const char * val15 = NULL,
const char * key16 = NULL,
const char * val16 = NULL,
const char * key17 = NULL,
const char * val17 = NULL,
const char * key18 = NULL,
const char * val18 = NULL,
const char * key19 = NULL,
const char * val19 = NULL,
const char * key20 = NULL,
const char * val20 = NULL )
static

Build a request DataMessage from an operation, request name and up to 20 key/value string pairs (NULL-terminated usage; pass pairs only as needed).

Parameters
operationHTTP_*-style operation id.
reqRequest name/path.
key1,key2,key3,key4,key5,key6,key7,key8,key9,key10,key11,key12,key13,key14,key15,key16,key17,key18,key19,key20Optional pair keys (NULL = unused).
val1,val2,val3,val4,val5,val6,val7,val8,val9,val10,val11,val12,val13,val14,val15,val16,val17,val18,val19,val20Optional pair values (NULL = unused).
Returns
A new DataMessage owned by the caller.

Definition at line 785 of file RequestClient.cpp.

References cmlabs::DataMessage::setInt(), and cmlabs::DataMessage::setString().

Referenced by TestServerLogin().

◆ finishRequest()

bool cmlabs::RequestClient::finishRequest ( RequestReply * reply)

Release a RequestReply obtained from postRequest() back to the client's pool.

Parameters
replyThe finished reply object.
Returns
true on success.
Warning
Do not access reply after this call.

Definition at line 387 of file RequestClient.cpp.

References cmlabs::RequestReply::clientRef, mutex, and requestMap.

Referenced by cmlabs::TestRequestClient::run(), SendRequestAndWaitForReply(), cmlabs::Test_RequestClient(), and cmlabs::RequestGateway::UnitTest().

◆ GetJSONReplyParameter()

std::string cmlabs::RequestClient::GetJSONReplyParameter ( const char * json,
const char * name )
static

Extract a named top-level string value from a JSON reply.

Parameters
jsonJSON text.
nameKey to find.
Returns
The value, or empty.

Definition at line 714 of file RequestClient.cpp.

References GetJSONValue(), jsmn_init(), jsmn_parse(), and JSMN_UNDEFINED.

Referenced by TestServerLogin().

◆ isConnected()

bool cmlabs::RequestClient::isConnected ( )
Returns
true when at least one gateway connection is currently up.

Definition at line 634 of file RequestClient.cpp.

References conMutex, and connections.

Referenced by TestServerLogin(), and waitForConnection().

◆ postRequest() [1/2]

RequestReply * cmlabs::RequestClient::postRequest ( DataMessage * msg)

Post a request asynchronously.

Assigns the next client reference id to msg (used to match the incoming reply), wraps it in a pooled RequestReply and queues it for the worker thread to dispatch to the best-connected gateway.

Parameters
msgRequest message (ownership transfers).
Returns
A RequestReply future owned by the client — wait on it, then release it with finishRequest(). NULL on local failure. Non-blocking.
Warning
finishRequest() deletes the RequestReply and both messages inside it (request and reply). Any pointer obtained via peek*() or waitForMessage(..., false) is invalid afterwards. A complete round-trip, taking ownership of the reply:
RequestReply* reply = client.postRequest(msg); // msg now owned by reply
if (reply) {
DataMessage* answer = reply->waitForMessage(3000, true); // take ownership
client.finishRequest(reply); // reply object gone now
if (answer) {
// ... use answer ...
delete answer; // caller must delete
}
}
#define HTTP_GET
GET.
The central Psyclone data container: a self-contained binary message with typed, named user entries.
static DataMessage * CreateRequestMessage(uint8 operation, const char *req, const char *key1=NULL, const char *val1=NULL, const char *key2=NULL, const char *val2=NULL, const char *key3=NULL, const char *val3=NULL, const char *key4=NULL, const char *val4=NULL, const char *key5=NULL, const char *val5=NULL, const char *key6=NULL, const char *val6=NULL, const char *key7=NULL, const char *val7=NULL, const char *key8=NULL, const char *val8=NULL, const char *key9=NULL, const char *val9=NULL, const char *key10=NULL, const char *val10=NULL, const char *key11=NULL, const char *val11=NULL, const char *key12=NULL, const char *val12=NULL, const char *key13=NULL, const char *val13=NULL, const char *key14=NULL, const char *val14=NULL, const char *key15=NULL, const char *val15=NULL, const char *key16=NULL, const char *val16=NULL, const char *key17=NULL, const char *val17=NULL, const char *key18=NULL, const char *val18=NULL, const char *key19=NULL, const char *val19=NULL, const char *key20=NULL, const char *val20=NULL)
Build a request DataMessage from an operation, request name and up to 20 key/value string pairs (NULL...
Future/handle for one in-flight request: holds the request message, the eventual reply,...
DataMessage * waitForMessage(uint32 timeoutMS, bool takeMessage=false)
Block for the reply message itself.

Definition at line 359 of file RequestClient.cpp.

References cmlabs::RequestReply::clientRef, cmlabs::RequestReply::giveRequestMessage(), lastRefID, mutex, outQ, cmlabs::QUEUED, requestMap, cmlabs::DataMessage::setReference(), and cmlabs::RequestReply::setStatus().

Referenced by cmlabs::TestRequestClient::run(), SendRequestAndWaitForReply(), SendRequestAndWaitForReplyObject(), cmlabs::Test_RequestClient(), and cmlabs::RequestGateway::UnitTest().

◆ postRequest() [2/2]

bool cmlabs::RequestClient::postRequest ( DataMessage * msg,
RequestCallbackFunction callback,
uint32 timeoutMS )

Post a request with a completion callback (fire-and-forget style).

Parameters
msgRequest message (ownership transfers).
callbackInvoked on an internal thread upon completion.
timeoutMSRequest timeout in ms.
Returns
true if queued.
Warning
Not yet implemented: the current implementation is a stub that always returns false without taking ownership of msg. Use postRequest(DataMessage*) plus RequestReply::setCallback(), or the blocking waits, instead.

Definition at line 382 of file RequestClient.cpp.

◆ receiveHTTPReply()

bool cmlabs::RequestClient::receiveHTTPReply ( HTTPReply * reply,
HTTPRequest * req,
NetworkChannel * channel,
uint64 conid )
virtual

NetworkReceiver hook: HTTP replies (when talking to a gateway over HTTP).

Reimplemented from cmlabs::NetworkReceiver.

Definition at line 485 of file RequestClient.cpp.

References channel.

◆ receiveMessage()

bool cmlabs::RequestClient::receiveMessage ( DataMessage * msg,
NetworkChannel * channel,
uint64 conid )
virtual

◆ receiveNetworkEvent()

bool cmlabs::RequestClient::receiveNetworkEvent ( NetworkEvent * evt,
NetworkChannel * channel,
uint64 conid )
virtual

◆ reconnect()

bool cmlabs::RequestClient::reconnect ( )

Force reconnection of gateway links.

Returns
true if reconnection was initiated.

Definition at line 664 of file RequestClient.cpp.

References channel, conMutex, and connections.

◆ run()

bool cmlabs::RequestClient::run ( )
protected

Worker loop: connection upkeep, outgoing queue, timeouts.

Returns
true to continue.

Definition at line 540 of file RequestClient.cpp.

References cmlabs::GetTimeAgeMS(), cmlabs::GetTimeNow(), cmlabs::Runnable::isRunning, outQ, sendRequest(), sendStatusNow(), and cmlabs::Runnable::shouldContinue.

Referenced by RequestClientRun.

◆ sendMessageToGateway()

◆ sendRequest()

bool cmlabs::RequestClient::sendRequest ( RequestReply * reply)
protected

Serialise and send one request to the best available gateway.

Returns
true if sent.

Definition at line 680 of file RequestClient.cpp.

References conMutex, connections, cmlabs::GetTimeNow(), cmlabs::NETWORKERROR, cmlabs::RequestReply::peekRequestMessage(), cmlabs::RequestReply::replyToRequest(), sendMessageToGateway(), cmlabs::SENT, sentCount, and cmlabs::RequestReply::setStatus().

Referenced by run().

◆ SendRequestAndWaitForJSON()

std::string cmlabs::RequestClient::SendRequestAndWaitForJSON ( RequestClient * client,
DataMessage * msg,
int timeoutMS )
static

Convenience: post msg on client, wait, and return the reply's JSON text.

Parameters
clientClient to use.
msgRequest (ownership transfers).
timeoutMSMax wait in ms.
Returns
JSON string, empty on failure. Blocking.

Definition at line 767 of file RequestClient.cpp.

References cmlabs::DataMessage::getString(), RequestClient(), and SendRequestAndWaitForReply().

Referenced by TestServerLogin().

◆ SendRequestAndWaitForReply()

DataMessage * cmlabs::RequestClient::SendRequestAndWaitForReply ( RequestClient * client,
DataMessage * msg,
int timeoutMS )
static

Convenience: post msg, wait, and return the reply message.

Parameters
clientClient to use.
msgRequest (ownership transfers).
timeoutMSMax wait in ms.
Returns
Reply owned by the caller, or NULL. Blocking.

Definition at line 737 of file RequestClient.cpp.

References finishRequest(), postRequest(), RequestClient(), and cmlabs::RequestReply::waitForMessage().

Referenced by SendRequestAndWaitForJSON().

◆ SendRequestAndWaitForReplyObject()

RequestReply * cmlabs::RequestClient::SendRequestAndWaitForReplyObject ( RequestClient * client,
DataMessage * msg,
int timeoutMS )
static

Convenience: post msg, wait, and return the whole RequestReply object.

Parameters
clientClient to use.
msgRequest (ownership transfers).
timeoutMSMax wait in ms.
Returns
The reply object (release with finishRequest()), or NULL. Blocking.

Definition at line 755 of file RequestClient.cpp.

References postRequest(), RequestClient(), and cmlabs::RequestReply::waitForResult().

Referenced by cmlabs::TestRequestClient::run().

◆ sendStatusNow()

uint32 cmlabs::RequestClient::sendStatusNow ( )
protected

Send a status/heartbeat message to all gateways.

Returns
Number of gateways notified.

Definition at line 588 of file RequestClient.cpp.

References conMutex, connections, LOG_SYSTEM, LogPrint, sendMessageToGateway(), and cmlabs::DataMessage::setString().

Referenced by run().

◆ TestServerLogin()

bool cmlabs::RequestClient::TestServerLogin ( const char * address,
uint16 port,
const char * username,
const char * password,
const char * reqAfterLogin )
static

Manual test: log in to a request server and issue a request.

Parameters
addressGateway host.
portGateway port.
usernameLogin user.
passwordLogin password.
reqAfterLoginRequest string to send after login.
Returns
true on success.

Definition at line 837 of file RequestClient.cpp.

References addGateway(), CreateRequestMessage(), GetJSONReplyParameter(), HTTP_POST, isConnected(), LogPrint, NOENC, RequestClient(), and SendRequestAndWaitForJSON().

◆ waitForConnection()

bool cmlabs::RequestClient::waitForConnection ( uint32 timeoutMS)

Block until a gateway connection is established.

Parameters
timeoutMSMax wait in ms.
Returns
true if connected in time. Blocking.

Definition at line 626 of file RequestClient.cpp.

References cmlabs::GetTimeAgeMS(), cmlabs::GetTimeNow(), isConnected(), and cmlabs::utils::Sleep().

Referenced by cmlabs::Test_RequestClient(), and cmlabs::RequestGateway::UnitTest().

◆ RequestClientRun

THREAD_RET THREAD_FUNCTION_CALL RequestClientRun ( THREAD_ARG arg)
friend

Thread entry point for the RequestClient worker loop.

Definition at line 704 of file RequestClient.cpp.

References RequestClient(), run(), THREAD_ARG, THREAD_FUNCTION_CALL, THREAD_RET, and thread_ret_val.

Referenced by RequestClient().

Member Data Documentation

◆ avgStats

MovingAverage cmlabs::RequestClient::avgStats
protected

Rolling round-trip statistics.

Definition at line 485 of file RequestClient.h.

◆ channel

NetworkChannel* cmlabs::RequestClient::channel
protected

Channel carrying the gateway connections.

Definition at line 475 of file RequestClient.h.

Referenced by addGateway(), receiveHTTPReply(), receiveMessage(), receiveNetworkEvent(), reconnect(), RequestClient(), and sendMessageToGateway().

◆ conMutex

utils::Mutex cmlabs::RequestClient::conMutex
protected

Guards ::connections.

Definition at line 478 of file RequestClient.h.

Referenced by isConnected(), reconnect(), sendRequest(), sendStatusNow(), and ~RequestClient().

◆ connections

std::list<RequestGatewayConnection> cmlabs::RequestClient::connections
protected

Configured gateways and their state.

Definition at line 476 of file RequestClient.h.

Referenced by addGateway(), isConnected(), receiveNetworkEvent(), reconnect(), sendRequest(), and sendStatusNow().

◆ lastRefID

uint64 cmlabs::RequestClient::lastRefID
protected

Last issued client reference id.

Definition at line 482 of file RequestClient.h.

Referenced by postRequest(), and RequestClient().

◆ manager

NetworkManager* cmlabs::RequestClient::manager
protected

Owned network stack for gateway links.

Definition at line 474 of file RequestClient.h.

Referenced by addGateway(), RequestClient(), and ~RequestClient().

◆ mutex

utils::Mutex cmlabs::RequestClient::mutex
protected

Guards request bookkeeping.

Definition at line 477 of file RequestClient.h.

Referenced by addGateway(), finishRequest(), postRequest(), receiveMessage(), receiveNetworkEvent(), and ~RequestClient().

◆ outQ

utils::WaitQueuePointer<RequestReply*> cmlabs::RequestClient::outQ
protected

Outgoing requests awaiting dispatch.

Definition at line 479 of file RequestClient.h.

Referenced by postRequest(), and run().

◆ receivedCount

uint64 cmlabs::RequestClient::receivedCount
protected

Total replies received.

Definition at line 484 of file RequestClient.h.

Referenced by receiveMessage(), and RequestClient().

◆ requestMap

std::map<uint64,RequestReply*> cmlabs::RequestClient::requestMap
protected

In-flight requests by client reference id.

Definition at line 480 of file RequestClient.h.

Referenced by finishRequest(), postRequest(), receiveMessage(), and ~RequestClient().

◆ sentCount

uint64 cmlabs::RequestClient::sentCount
protected

Total requests sent.

Definition at line 483 of file RequestClient.h.

Referenced by RequestClient(), and sendRequest().

◆ threadID

uint32 cmlabs::RequestClient::threadID
protected

Worker thread id.

Definition at line 481 of file RequestClient.h.

Referenced by RequestClient().


The documentation for this class was generated from the following files: