[PATCH] Add $upstream_cache_key

Kirill A. Korinsky kirill at korins.ky
Thu May 23 09:52:13 UTC 2024


Greetings,

Here is a patch that exposes the constructed cache key as
$upstream_cache_key variable.

Sometimes it's quite useful when debugging complicated setups and fighting
some typos.

index 2ce9f2114..561108681 100644
--- src/http/ngx_http_upstream.c
+++ src/http/ngx_http_upstream.c
@@ -23,6 +23,8 @@ static ngx_int_t ngx_http_upstream_cache_check_range(ngx_http_request_t *r,
     ngx_http_upstream_t *u);
 static ngx_int_t ngx_http_upstream_cache_status(ngx_http_request_t *r,
     ngx_http_variable_value_t *v, uintptr_t data);
+static ngx_int_t ngx_http_upstream_cache_key(ngx_http_request_t *r,
+    ngx_http_variable_value_t *v, uintptr_t data);
 static ngx_int_t ngx_http_upstream_cache_last_modified(ngx_http_request_t *r,
     ngx_http_variable_value_t *v, uintptr_t data);
 static ngx_int_t ngx_http_upstream_cache_etag(ngx_http_request_t *r,
@@ -414,6 +416,10 @@ static ngx_http_variable_t  ngx_http_upstream_vars[] = {
       ngx_http_upstream_cache_status, 0,
       NGX_HTTP_VAR_NOCACHEABLE, 0 },
 
+    { ngx_string("upstream_cache_key"), NULL,
+      ngx_http_upstream_cache_key, 0,
+      NGX_HTTP_VAR_NOCACHEABLE, 0 },
+
     { ngx_string("upstream_cache_last_modified"), NULL,
       ngx_http_upstream_cache_last_modified, 0,
       NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_NOHASH, 0 },
@@ -5990,6 +5996,47 @@ ngx_http_upstream_cache_status(ngx_http_request_t *r,
 }
 
 
+static ngx_int_t
+ngx_http_upstream_cache_key(ngx_http_request_t *r,
+    ngx_http_variable_value_t *v, uintptr_t data)
+{
+    size_t             len;
+    ngx_uint_t         i;
+    ngx_str_t         *key;
+    ngx_http_cache_t  *c;
+
+    if (r->cache == NULL || r->cache->keys.nelts == 0) {
+        v->not_found = 1;
+        return NGX_OK;
+    }
+
+    c = r->cache;
+
+    key = c->keys.elts;
+    len = 0;
+    for (i = 0; i < c->keys.nelts; i++) {
+        len += key[i].len;
+    }
+
+    v->data = ngx_pcalloc(r->pool, len);
+    if (v->data == 0) {
+        return NGX_ERROR;
+    }
+
+    v->len = 0;
+    for (i = 0; i < c->keys.nelts; i++) {
+        memcpy(v->data + v->len, key[i].data, key[i].len);
+        v->len += key[i].len;
+    }
+
+    v->valid = 1;
+    v->no_cacheable = 0;
+    v->not_found = 0;
+
+    return NGX_OK;
+}
+
+
 static ngx_int_t
 ngx_http_upstream_cache_last_modified(ngx_http_request_t *r,
     ngx_http_variable_value_t *v, uintptr_t data)


-- 
wbr, Kirill



More information about the nginx mailing list