Handling composite asynchronous functions in c++ - c++

I have an API which sends/receives request/data from the serve in an asynchronous manner. The API comes with request functions and their corresponding callbacks.
I intend to use this API but a single function in my application can send multiple asynchronous requests to the server before it starts doing anything on its own. Is there any framework to manage composite asynchronous functions.
An example would be
void doSomething()
{
sendRequestDataItem1(); //receives result in getDataItem1()
sendRequestDataItem2(); //receives result in getDataItem2()
sendRequestDataItem3(); //receives result in getDataItem3()
//this function can either be a composite handler or something else
NowDoSomethingMore();
}
Thanks
Shiv

I would recommend boost::signals, it is pretty easy to use.
If you need thread safety (guessing?) boost::siganals2 is a good place to start.

Related

OpenSSL 1.1.1d - Async use of SSL_CTX_set_cert_verify_callback?

Certificate validation in general requires asynchronous operations such as: OCSP/CRL fetch.
On the other hand, the callback from SSL_CTX_set_cert_verify_callback expects a synchronous result:
1 (success) / 0 (failure). (reference).
I find it kind of odd that any validation of this type is expected to be synchronous.
Is there an alternative API for certificate chain validation that supports asynchronous operations?
In theory I think you should be able to use the OpenSSL ASYNC API to do this. Normally this is used by asynchronous capable engines, but I don't see why it wouldn't also work in applications.
Firstly you would need to put your SSL object into ASYNC mode using the function call SSL_set_mode() and specifying SSL_MODE_ASYNC. You can also do this at the SSL_CTX level using SSL_CTX_set_mode(). See:
https://www.openssl.org/docs/man1.1.1/man3/SSL_set_mode.html
Once that is done you need to ensure your application is prepared to handle the return value SSL_ERROR_WANT_ASYNC from any call to SSL_get_error(). See:
https://www.openssl.org/docs/man1.1.1/man3/SSL_get_error.html
Your application can then implement a callback in the normal way via SSL_CTX_set_cert_verify_callback. If it needs to temporarily pause operation to wait for some asynchronous operation to complete then the callback should call ASYNC_pause_job(). See:
https://www.openssl.org/docs/man1.1.1/man3/ASYNC_pause_job.html
This will have the effect of control returning to your main application and SSL_get_error() will return SSL_ERROR_WANT_ASYNC. You will need to implement some mechanism for your application to know when asynchronous processing is complete. When it is, then simply retry the SSL I/O call that was previously paused. Note: this must occur on the same thread that the original call was made from. Your callback will then resume from the point at which it previously paused.

about C++ rest sdk and synchronous calls

I have started working with 'cpp rest sdk'. The key point I understood it that all requests and response are asynchronous using the means of PPL. This is fine to boost scalability and performance of the application.
The question I have is weather is any way to request and wait for a response in a 'synchronous' fashion.
I found the following web page which seems to work fine and it claims to make call in synchronous way. Is it so?
Does a call to task::get() guarantees that the function returns when the response is ready to be read?
The major idea of asynchronous programming is to chain all parts you want to have executed sequentially. If you want the program to wait until the sequence is finished, you can end the chain with .wait()
client.request(web::http::methods::GET, U("/foo.html"))
.then(/*some lambda*/)
.then(/*some lambda*/) //and so on
.wait(); //stop here until the chain is executed
Similarly, you can also use get() which also calls wait() but further returns the result of the task.

Managing asynchronous communication: how to examine response received in another thread

I have a dispatcher thread and a listener thread. When I dispatch a command, I want to wait for response before I send follow up command. Moreover I need to examine the respond before I can proceed with 2nd command, the least of which is to confirm the response is received and everything is okay. My pseudo code is below:
void MainWindow::downloadData()
{
dispatcher->getInfo(); // sends command
// QString response = receiver->response() // idealy I would like to check response but since its async, i can't really do that!
dipatcher->askData(); // the 2nd command and so forth
}
Is there any elegant way to solve this issue? The only way I can think of is if I use the same thread and all calls are blocking but that's not necessarily a good solution.
In Qt, I could use signals and slots to connect them in cascading manner so when the first signal is triggered it initiates the whole sequence of operation (each slot emitting a new signal) but seems rather dirty as well.
One of the most robust ways to handle asynchronous events and process a chains/graphs of actions upon these events are FSMs. Qt provides a basis for implementing FSMs with its Qt-State machine framework. I'd suggest to go this way. Unfortunately all the examples provided by Qt for FSM are dealing with GUIs and animations.
The advantage of FSM approach is, FSMs can be represented both as graphs and as tables. The first option is great for understanding, the second for validation, that there are no endless loops and "dead" ends.
I've built on basis of Qt-FSM framework own framework for defining FSMs in a domain specific language. I use it for controlling a complex machine having couple of sensors actors all working asynchronously. Using DSL helps me to implement in higher abstraction - in the abstraction level of FSM-graphs.

Interfacing with a daemon in C++ with sockets

I'm writing a daemon that needs to both run in the background and take care of tasks and also receive input directly from a frontend. I've been attempting to use sockets to take care of this task, however, I can't get it to work properly since sockets pause the program while waiting for a connection. Is there anyway to get around this?
I'm using the socket wrappers provided at http://linuxgazette.net/issue74/tougher.html
Thank you for any and all help
You will need to use threads to make the socket operations asynchronous. Or use some library that has already implemented it, one of the top ones is Boost Asio.
There are a few ways to handle this problem. This most common is using an event loop and something like libevent. Then you use non-blocking sockets.
Doing this in an event driven fashion can require a big shift in your program logic. But doing it with threads has its own complexities and isn't clearly a better choice.
Usually the daemons use event loops to avoid the problem of waiting for events.
It's the smartest solution to the problem that you present (do not wait to an asynchronous event). รง
Althought, usually the entire daemon is build over the event loop and it's callback architecture, and can cause a partial rewritting, so usually the quick and dirty solution is creating a separate thread to handle those events wich usually creates more bugs than it solves. So, use an event loop:
libevent.
glib event loop.
libev.
boost::asio
...
From your description, you have already divided your application into a frontend (receiving input) and backend (socket handling and tasks). If the input from the frontend is sent over the socket (via the backend) rather receiving input from the socket then it seems like you are describing a client and not a server. Client programs are typically not implemented as daemons.
You have created a blocking socket and need to either monitor in a separate thread execution a thread or even separate process) or make a non-blocking socket and poll frequently for updates.
The link to the LinuxGazette is a basic intro to network programming. If you would like a little more depth then take a look at Beej's Guide to Network Programming where the various API calls available to you are explained in a little detail.. and will, perhaps, make you appreciate more wrapper libraries such as Boost::ASIO.
Can be worth retaining control of the event loop yourself - its no complicated and provides flexibility down the track.
"C++ pseudo-code" for an event loop.
while (!done)
{
bool workDone = false;
// Loop over each event source or internal worker
for each module
{
// If it has work to do, do some.
if (module.hasWorkDoTo())
{
// Generally, do as little work as possible; e.g. process a single event for this module.
// But tinker with this to manage priorities if need be.
// E.g. Maybe allow the GUI to flush its queue.
module.doSomeWork();
workDone = true;
}
}
if (!workDone)
{
// System idle. No Sleep for a bit so we have benign idle baheviour.
nanosleep(...);
}
}

What is IconnectionPoint and EventHandling

Trying to understand What is IConnectionPoint and how this is connected to IConnectionPointContainer,IEnumConnectionPoints,IEnumConnections and EventHandling.
Read the artcicles from MSDN and CodeProject which is explaining a about other methods like: QueryInterface() and otherthings.
I am unable to figure out how all these things(IConnectionPointContainer,IEnumConnectionPoints,IEnumConnections) are interconnected with eachother and event Handling.
I just want to create a simpleClient which Will trigger an event in COM object.
If there are any articles or code snippet that can explain how things are related to each other with simple and small chunk of code will be helpfull.
Worth mentioning that I have started development in C recently, a beginner.
Edit #sharptooth
For the Line "typically your client will receive events and the COM object will trigger those events. "
From many articles, What I understood is When we use connection points at that point,
the client exposes a set of methods that the server uses.
I am just Outlining portion of the article from TechRepublich:
Client server vs. sink source
So the main difference between normal programming with COM in a standard client-server system and using connection points is that in the standard client-server case, the server exposes a list of methods that the client employs, and in the connection point case, the client exposes a set of methods that the server uses.
Looks like you get the big picture wrong. Typically your client will receive events and the COM object will trigger those events. To achieve this the client requests (QueryInterface()) the IConnectionPointContainer interface, calls IConnectionPointContainer::FindConnectionPoint() and IConnectionPoint::Advise() and passes a pointer to itself or some subobject there.
The client will have to implement some events interface (the one GUID of which is passed into IConnectionPointContainer::FindConnectionPoint()). Once subscribed (advised) the client will receive calls from the COM server - the events.
Typically the COM server does something routinely and decides to notify clients of it (say a user moves the mouse in an ActiveX control) - it just gets an array of pointers to event receivers and calls a method it wants on that interface.
COM events are in fact an implementation of callbacks. The same way you use callback in C++ (or C or any other languages supporting function pointers or interfaces) you use events in COM. Yes, you're right that when the server triggers the event the client in fact acts as a server reacting to the event. That's a callback scenario - the other code calls your functionality. In this case the server calls your implementation of the events interface.
These two articles provide useful information:
https://devblogs.microsoft.com/oldnewthing/?p=4113
https://devblogs.microsoft.com/oldnewthing/20130612-00/?p=4103
What #sharptooth forgot to mention is, the pointer passed to IConnectionPoint::Advise must be a pointer to a COM object.
This means It must not only implement the particular events interface but also the IUnknown interface.