Skip to content

Commit bcf1ed0

Browse files
authored
server: update abort mechanism to handle HTTP connection closure (#3112)
1 parent 934d4b3 commit bcf1ed0

File tree

1 file changed

+16
-24
lines changed

1 file changed

+16
-24
lines changed

examples/server/server.cpp

+16-24
Original file line numberDiff line numberDiff line change
@@ -843,33 +843,25 @@ int main(int argc, char ** argv) {
843843
wparams.progress_callback_user_data = &user_data;
844844
}
845845

846-
// examples for abort mechanism
847-
// in examples below, we do not abort the processing, but we could if the flag is set to true
848-
849-
// the callback is called before every encoder run - if it returns false, the processing is aborted
850-
{
851-
static bool is_aborted = false; // NOTE: this should be atomic to avoid data race
852-
853-
wparams.encoder_begin_callback = [](struct whisper_context * /*ctx*/, struct whisper_state * /*state*/, void * user_data) {
854-
bool is_aborted = *(bool*)user_data;
855-
return !is_aborted;
856-
};
857-
wparams.encoder_begin_callback_user_data = &is_aborted;
858-
}
859-
860-
// the callback is called before every computation - if it returns true, the computation is aborted
861-
{
862-
static bool is_aborted = false; // NOTE: this should be atomic to avoid data race
863-
864-
wparams.abort_callback = [](void * user_data) {
865-
bool is_aborted = *(bool*)user_data;
866-
return is_aborted;
867-
};
868-
wparams.abort_callback_user_data = &is_aborted;
869-
}
846+
// tell whisper to abort if the HTTP connection closed
847+
wparams.abort_callback = [](void *user_data) {
848+
// user_data is a pointer to our Request
849+
auto req_ptr = static_cast<const httplib::Request*>(user_data);
850+
return req_ptr->is_connection_closed();
851+
};
852+
wparams.abort_callback_user_data = (void*)&req;
870853

871854
if (whisper_full_parallel(ctx, wparams, pcmf32.data(), pcmf32.size(), params.n_processors) != 0) {
855+
// handle failure or early abort
856+
if (req.is_connection_closed()) {
857+
// log client disconnect
858+
fprintf(stderr, "client disconnected, aborted processing\n");
859+
res.status = 499; // Client Closed Request (nginx convention)
860+
res.set_content("{\"error\":\"client disconnected\"}", "application/json");
861+
return;
862+
}
872863
fprintf(stderr, "%s: failed to process audio\n", argv[0]);
864+
res.status = 500; // Internal Server Error
873865
const std::string error_resp = "{\"error\":\"failed to process audio\"}";
874866
res.set_content(error_resp, "application/json");
875867
return;

0 commit comments

Comments
 (0)