Canceling a process on the server

I am using Vapor on a mac server. The server makes lengthy computation so I need to allow the client to be able to cancel the computation.

On the client side, I have the following Javascript code to send a POST request and wait for the result:

async function doSomething(text) {
    controller = new AbortController()
    const response = await fetch("http://" + website + "/api/dosomething",
        {
            method: 'POST',
            signal: controller.signal,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
        },
        body: JSON.stringify({ text: text })
        })
    const results = await response.json()
    return results
}

as well as a button to cancel the process:

async function cancelquery() {
    controller.abort()
}

This works fine on the client side, i.e., the client does no longer wait for the result when I click the Cancel button. However, I don't know how to catch the "abort" signal on the server side to stop the computation. Is there any external variable, method or event in Vapor that I could use to know that the client sent an Abort signal?

What happens on a fetch abort at the network level is described in the spec in § 4.6, specifically in step 16:

  1. If aborted, then:

  2. If fetchParams is aborted, then:
    1. Set response’s aborted flag.
    2. If stream is readable, then error stream with the result of deserialize a serialized abort reason given fetchParams’s controller’s serialized abort reason and an implementation-defined realm.

  3. Otherwise, if stream is readable, error stream with a TypeError.

  4. If connection uses HTTP/2, then transmit an RST_STREAM frame.

  5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.

    For instance, the user agent could keep the connection open if it knows there’s only a few bytes of transfer remaining on a reusable connection. In this case it could be worse to close the connection and go through the handshake process again for the next fetch.

Thus, what Vapor sees is dependent on exactly where in the flow we are, but typically this will manifest as a connection being closed.

In most cases this will be ignored, but if you are streaming a body upload then it will manifest with the body stream terminating with an error.

1 Like

thanks, this solved my problem.