Parcourir la source

Offload slow HTTP asset and image responses

SybexXx il y a 1 jour
Parent
commit
73f095ce22

+ 15 - 3
code/components/jomjol_fileserver_ota/server_help.cpp

@@ -6,6 +6,8 @@
 #include <sys/unistd.h>
 #include <sys/stat.h>
 #include <dirent.h>
+#include <memory>
+#include <new>
 #include "esp_err.h"
 #include "esp_log.h"
 #include "esp_http_server.h"
@@ -21,7 +23,6 @@ static const char *TAG = "SERVER HELP";
 
 string SUFFIX_ZW = "_tmp";
 
-char scratch[SERVER_HELPER_SCRATCH_BUFSIZE];
 
 bool endsWith(std::string const &str, std::string const &suffix)
 {
@@ -128,8 +129,19 @@ esp_err_t send_file(httpd_req_t *req, std::string filename)
         set_content_type_from_file(req, filename.c_str());
     }
 
-    /* Retrieve the pointer to scratch buffer for temporary storage */
-    char *chunk = scratch;
+    // Each async transfer owns its buffer; a process-global scratch array would
+    // race if another file response is ever served from a different task.
+    std::unique_ptr<char[]> chunkBuffer(
+        new (std::nothrow) char[SERVER_HELPER_SCRATCH_BUFSIZE]);
+    if (!chunkBuffer)
+    {
+        fclose(fd);
+        httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Not enough memory for file response");
+        logSlowTransfer("buffer allocation failed");
+        return ESP_ERR_NO_MEM;
+    }
+
+    char *chunk = chunkBuffer.get();
     size_t chunksize;
 
     do

+ 97 - 0
code/components/jomjol_wlan/basic_auth.cpp

@@ -109,6 +109,86 @@ esp_err_t dispatch_camera_http_request_async(httpd_req_t *req,
     return ESP_OK;
 }
 
+
+// General bounded worker for responses that may block on socket transmission.
+// Unlike camera requests, normal asset/image responses may arrive concurrently,
+// so they are queued instead of rejected while another transfer is active.
+static QueueHandle_t httpAsyncRequestQueue = NULL;
+
+struct AsyncHttpRequest
+{
+    httpd_req_t *request;
+    basic_auth_async_handler_t handler;
+    char handlerName[32];
+    char uri[128];
+    int64_t startUs;
+};
+
+static void async_http_request_task(void *argument)
+{
+    (void)argument;
+    AsyncHttpRequest work = {};
+
+    while (httpAsyncRequestQueue != NULL &&
+           xQueueReceive(httpAsyncRequestQueue, &work, portMAX_DELAY) == pdTRUE)
+    {
+        const esp_err_t result = work.handler(work.request);
+        const int64_t elapsedUs = esp_timer_get_time() - work.startUs;
+
+        if (elapsedUs >= 100000)
+        {
+            LogFile.WriteToFile(ESP_LOG_WARN, TAG,
+                                std::string("Async HTTP response: ") + work.handlerName +
+                                " " + work.uri + " took " +
+                                std::to_string(static_cast<long long>(elapsedUs / 1000)) +
+                                " ms (result=" + std::to_string(static_cast<int>(result)) + ")");
+        }
+
+        httpd_req_async_handler_complete(work.request);
+    }
+    vTaskDelete(NULL);
+}
+
+esp_err_t dispatch_http_request_async(httpd_req_t *req,
+                                       basic_auth_async_handler_t handler,
+                                       const char *handler_name)
+{
+    if (req == NULL || handler == NULL) {
+        return ESP_ERR_INVALID_ARG;
+    }
+
+    // Preserve normal serving behaviour if worker initialization failed.
+    if (httpAsyncRequestQueue == NULL) {
+        return handler(req);
+    }
+
+    httpd_req_t *asyncRequest = NULL;
+    const esp_err_t copyResult = httpd_req_async_handler_begin(req, &asyncRequest);
+    if (copyResult != ESP_OK) {
+        httpd_resp_set_status(req, "503 Service Unavailable");
+        httpd_resp_sendstr(req, "Could not queue HTTP response");
+        return ESP_OK;
+    }
+
+    AsyncHttpRequest work = {};
+    work.request = asyncRequest;
+    work.handler = handler;
+    strlcpy(work.handlerName, handler_name != NULL ? handler_name : "http",
+            sizeof(work.handlerName));
+    strlcpy(work.uri, asyncRequest->uri, sizeof(work.uri));
+    work.startUs = esp_timer_get_time();
+
+    if (xQueueSend(httpAsyncRequestQueue, &work, 0) != pdTRUE) {
+        // Queue full: complete the async copy and return an explicit overload
+        // response on the original request rather than blocking the HTTP task.
+        httpd_req_async_handler_complete(asyncRequest);
+        httpd_resp_set_status(req, "503 Service Unavailable");
+        httpd_resp_sendstr(req, "HTTP response worker is busy");
+    }
+
+    return ESP_OK;
+}
+
 // All URI handlers are registered through APPLY_BASIC_AUTH_FILTER. Measuring here
 // gives us a common duration for every HTTP endpoint, including static HTML/CSS/JS
 // and image handlers. Time spent waiting in the ESP-IDF server queue is not included.
@@ -177,6 +257,23 @@ void init_basic_auth() {
                                 "Failed to start asynchronous camera request worker");
         }
     }
+
+    // File and image transfers can block in httpd_resp_send_chunk() when the
+    // client/network is slow. Keep them out of the single HTTP server task.
+    if (httpAsyncRequestQueue == NULL) {
+        httpAsyncRequestQueue = xQueueCreate(4, sizeof(AsyncHttpRequest));
+        if (httpAsyncRequestQueue == NULL ||
+            xTaskCreatePinnedToCore(async_http_request_task, "http_io",
+                                    8 * 1024, NULL, tskIDLE_PRIORITY + 3,
+                                    NULL, 1) != pdPASS) {
+            if (httpAsyncRequestQueue != NULL) {
+                vQueueDelete(httpAsyncRequestQueue);
+                httpAsyncRequestQueue = NULL;
+            }
+            LogFile.WriteToFile(ESP_LOG_ERROR, TAG,
+                                "Failed to start asynchronous HTTP response worker");
+        }
+    }
 }
 
 static char *http_auth_basic(const char *username, const char *password)

+ 3 - 0
code/components/jomjol_wlan/basic_auth.h

@@ -7,6 +7,9 @@ using basic_auth_async_handler_t = esp_err_t (*)(httpd_req_t *req);
 esp_err_t dispatch_camera_http_request_async(httpd_req_t *req,
                                               basic_auth_async_handler_t handler,
                                               const char *handler_name);
+esp_err_t dispatch_http_request_async(httpd_req_t *req,
+                                       basic_auth_async_handler_t handler,
+                                       const char *handler_name);
 esp_err_t basic_auth_request_filter(httpd_req_t *req, esp_err_t original_handler(httpd_req_t *));
 
 #define APPLY_BASIC_AUTH_FILTER(method) [](httpd_req_t *req){ return basic_auth_request_filter(req, method); }

+ 30 - 5
code/main/server_main.cpp

@@ -451,7 +451,7 @@ esp_err_t starttime_get_handler(httpd_req_t *req)
 }
 
 
-esp_err_t hello_main_handler(httpd_req_t *req)
+static esp_err_t hello_main_handler_worker(httpd_req_t *req)
 {
 #ifdef DEBUG_DETAIL_ON      
     LogFile.WriteHeapInfo("hello_main_handler - Start");
@@ -544,6 +544,12 @@ esp_err_t hello_main_handler(httpd_req_t *req)
 }
 
 
+
+esp_err_t hello_main_handler(httpd_req_t *req)
+{
+    return dispatch_http_request_async(req, hello_main_handler_worker, "static file");
+}
+
 esp_err_t img_tmp_handler(httpd_req_t *req)
 {
     char filepath[50];
@@ -577,7 +583,7 @@ static esp_err_t raw_jpg_capture_worker(httpd_req_t *req)
     return GetRawJPG(req, previewCapture);
 }
 
-esp_err_t img_tmp_virtual_handler(httpd_req_t *req)
+static esp_err_t img_tmp_virtual_handler_worker(httpd_req_t *req)
 {
 #ifdef DEBUG_DETAIL_ON
     LogFile.WriteHeapInfo("img_tmp_virtual_handler - Start");
@@ -598,11 +604,10 @@ esp_err_t img_tmp_virtual_handler(httpd_req_t *req)
     const std::string fileName(filename);
     ESP_LOGD(TAG, "File to upload: %s", fileName.c_str());
 
-    // A raw camera capture can take several seconds. Keep it off the single
-    // HTTP server task so status, log and static-file requests remain responsive.
+    // The raw camera path is dispatched separately to the serialized camera worker.
     if (fileName == "raw.jpg")
     {
-        return dispatch_camera_http_request_async(req, raw_jpg_capture_worker, "raw capture");
+        return ESP_FAIL;
     }
 
     // Serve alg.jpg, alg_roi.jpg or digit and analog ROIs.
@@ -617,6 +622,26 @@ esp_err_t img_tmp_virtual_handler(httpd_req_t *req)
     return img_tmp_handler(req);
 }
 
+esp_err_t img_tmp_virtual_handler(httpd_req_t *req)
+{
+    char filepath[50];
+    char *base_path = (char*) req->user_ctx;
+    const char *filename = get_path_from_uri(filepath, base_path,
+                                             req->uri + sizeof("/img_tmp/") - 1, sizeof(filepath));
+    if (filename == NULL)
+    {
+        httpd_resp_send_err(req, HTTPD_414_URI_TOO_LONG, "Filename too long");
+        return ESP_FAIL;
+    }
+
+    if (strcmp(filename, "raw.jpg") == 0)
+    {
+        return dispatch_camera_http_request_async(req, raw_jpg_capture_worker, "raw capture");
+    }
+
+    return dispatch_http_request_async(req, img_tmp_virtual_handler_worker, "image response");
+}
+
 esp_err_t sysinfo_handler(httpd_req_t *req)
 {
     // Take one snapshot of resource and card information for this response.