Sending intermediary responses on API call - node.js

I'm not sure how to achieve this behavior from our server:
Backend behavior
client sends request
server responds in <1s with an intermediary response - something like step 1/2
server start performing the computation
when done, server sends back the finalized task - step 2/2 finished
Frontend behavior
send request
act on the intermediary step being finished - purpose of this: the entire flow is more engaging
act on the request being step
I would like to all this by calling only one API endpoint. Is this possible?

Related

Send updates about the state of a running HTTP request to the client

I would like to send updates of a running HTTP request to the client to tell it at what stage the request-triggered process currently is.
The process behind the request does currently the following things (in this order):
Client-side:
Client sends an HTTP Request (upload of a file) to the server
Server-side:
Takes the uploaded file
Encrypt it
Upload it to an archive storage
Return response to the client
(Meanwhile, the client does not know what currently happens)
Client-side:
Get response and show it to the user
I want to tell the client at what stage the process is, like “Uploading done. Encrypting…” and so on.
Is there a way to realize that, or am I missing something? Is it even possible to do?
Frameworks I'm using:
Client: Next.js
Server: Hapi.dev for API development
Thanks
You can send non-final 1xx header responses for your http request as described here.

Sending a response after jobs have finished processing in Express

So, I have Express server that accepts a request. The request is web scraping that takes 3-4 minute to finish. I'm using Bull to queue the jobs and processing it as and when it is ready. The challenge is to send this results from processed jobs back as response. Is there any way I can achieve this? I'm running the app on heroku, but heroku has a request timeout of 30sec.
You don’t have to wait until the back end finished do the request identified who is requesting . Authenticate the user. Do a res.status(202).send({message:”text});
Even though the response was sended to the client you can keep processing and stuff
NOTE: Do not put a return keyword before res.status...
The HyperText Transfer Protocol (HTTP) 202 Accepted response status code indicates that the request has been accepted for processing, but the processing has not been completed; in fact, processing may not have started yet. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place.
202 is non-committal, meaning that there is no way for the HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing.
You always need to send response immediately due to timeout. Since your process takes about 3-4 minutes, it is better to send a response immediately mentioning that the request was successfully received and will be processed.
Now, when the task is completed, you can use socket.io or web sockets to notify the client from the server side. You can also pass a response.
The client side also can check continuously if the job was completed on the server side, this is called polling and is required with older browsers which don't support web sockets. socket.io falls back to polling when browsers don't support web sockets.
Visit socket.io for more information and documentation.
Best approach to this problem is socket.io library. It can send data to client send whenever you want. It triggers a function on client side which receives the data. Socket.io supports different languages and it is really ease to use.
website link
Documentation Link
create a jobs table in a database or persistant storage like redis
save each job in the table upon request with a unique id
update status to running on starting the job
sent HTTP 202 - Accepted
At the client implement a polling script, At the server implement a job status route/api. The api accept a job id and queries the job table and respond with the status
When the job is finished update the job table with status completed, when the jon is errored updated the job table with status failed and maybe a description column to store the cause for error
This solution makes your system horizontaly scalable and distributed. It also prevents the consequences of unexpected connection drops. Polling interval depends on average job completion duration. I would recommend an average interval of 5 second
This can be even improved to store job completion progress in the jobs table so that the client can even display a progress bar
->Request time out occurs when your connection is idle, different servers implement in a different way so timeout time differs
1)The solution for this timeout problem would be to make your connections open(constant), that is the connection between client and servers should remain constant.
So for such scenarios use WebSockets, which ensures that after the initial request and response handshake between client and server the connection stays open.
there are many libraries to implement realtime connection.Eg Pubnub,socket.io. This is the same technology used for live streaming.
Node js can handle many concurrent connections and its lightweight too, won't use many resources too.

How to send multiple HTTP responses in time (Report server processing state) without sockets

I am sending file to my NodeJS Express based server by HTTP POST.
After image is received by server, server starts processing. It takes few seconds and there is few steps in processing (Transform image, OCR, saving, etc).
I want to keep user informed while he waiting for server to process image with some responses ("Transforming image...","Converting...","Finishing...").
So I need some way to send data to user before actual end of processing and final response HTTP status and data.
Is this possible just by HTTP responses or I need to implement something different?
It is not possible for http to send two responses, you can build another api which the user can hit and get the status of the last request made, once you give an order to process the request, you can send the response as processing and a unique id using which the user can check the status (2nd api), and once the user hits another api to know the status, you can give him the current status as completed or in progress.

How Request and Response will got process in service stack?

I am using service stack to build the create RESTful services, not have depth knowledge of it. This works as sending request and getting response back. I have scenario and my question is depends on it.
Scenario: I am sending request from browser or any client where I am able to send request to server. Consider server will take 3 seconds to process single request and send back response to browser. After one second, I have sent another request to server from same browser(client). Now I am getting response of second request which I sent later.
Question 1: What is happening behind with the first request which I did not get response.
Question 2: How I can stop processing of orphan request.
Edit : I have used IIS server to host services.
ServiceStack executes requests concurrently on multithreaded web servers, whether you're hosting on ASP.NET/IIS or self-hosted so 2 concurrent requests are running concurrently on different threads. There are different scenarios possible if you're executing async tasks in your Services in which it frees up the thread to execute different tasks, but the implementation details are largely irrelevant here.
HTTP Web Requests are each executed to their end, even when its client connection is lost your Services are never notified and no Exceptions are raised.
But for long running Services you can enable the high-level ServiceStack's Cancellable Requests Feature which enables a way for clients to cancel long running requests.

node.js built in support for handling requests for same data

In my node.js server app I'm providing a service to my js client that performs some handling of remote api's.
It might very well be possible that two different clients request the same information. Say client 1 requests information, then before client 1's request is fully handled (remote api's didn't returns their response yet) client 2 is requesting the same data. What I'd want to is to wait for client 1 data to be ready and then write it to both client 1 and 2.
This seems to me like a very common issue and I was wondering if there was any library or built-in support in connect or express that supports this issue.
You might not want to use HTTP for providing the data to the client. Reasons:
If the remote API is taking a lot of time to process you will risk the client request to timeout, or the browser to repeat the request.
You will have to share some state between requests which is not a good practice.
Have a look at websockets (socket.io would be a place to start). With them you can push data from the server to the client. In your scenario, clients will perform the request to the server, which will return 202 and when the remote API will respond, the server will push the data to the clients using websockets.

Resources