sachaarbonel commited on
Commit
02b25fa
·
unverified ·
1 Parent(s): 7e3c27c

server: update abort mechanism to handle HTTP connection closure (#3112)

Browse files
Files changed (1) hide show
  1. examples/server/server.cpp +16 -24
examples/server/server.cpp CHANGED
@@ -843,33 +843,25 @@ int main(int argc, char ** argv) {
843
  wparams.progress_callback_user_data = &user_data;
844
  }
845
 
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
- }
870
 
871
  if (whisper_full_parallel(ctx, wparams, pcmf32.data(), pcmf32.size(), params.n_processors) != 0) {
 
 
 
 
 
 
 
 
872
  fprintf(stderr, "%s: failed to process audio\n", argv[0]);
 
873
  const std::string error_resp = "{\"error\":\"failed to process audio\"}";
874
  res.set_content(error_resp, "application/json");
875
  return;
 
843
  wparams.progress_callback_user_data = &user_data;
844
  }
845
 
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;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
853
 
854
  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
+ }
863
  fprintf(stderr, "%s: failed to process audio\n", argv[0]);
864
+ res.status = 500; // Internal Server Error
865
  const std::string error_resp = "{\"error\":\"failed to process audio\"}";
866
  res.set_content(error_resp, "application/json");
867
  return;