]> git.kaiwu.me - njs.git/commitdiff
Modules: preserve shared dictionary numbers in state files
authorDmitry Volyntsev <xeioex@nginx.com>
Tue, 1 Dec 2026 15:19:11 +0000 (07:19 -0800)
committerDmitry Volyntsev <xeioexception@gmail.com>
Tue, 1 Dec 2026 21:42:41 +0000 (13:42 -0800)
Previously, the shared dictionary state writer formatted numbers with
six fractional digits in a fixed-size buffer.  Small values rounded to
zero, ordinary fractions lost precision, large values were truncated,
and non-finite values produced invalid JSON that prevented a subsequent
startup.

Use the engine-independent dtoa formatter to write a round-trip decimal
representation, with a buffer sized by the formatter.  Quote non-finite
values as "NaN", "Infinity", and "-Infinity" in JSON state files and
parse them back on load, while preserving the sign of zero and the
existing JSON state schema.

The issue was introduced in eca03622 (0.9.1).

nginx/ngx_js_shared_dict.c
nginx/t/js_shared_dict_state_numbers.t [new file with mode: 0644]

index ddb8617adba43dbee8f81c60d0b264df67ca7f50..b1729a0c48573115e0062a5d459cbc70fd6d8183 100644 (file)
@@ -7,6 +7,8 @@
 
 #include <ngx_config.h>
 #include <ngx_core.h>
+#include <math.h>
+#include <njs_dtoa.h>
 #include "ngx_js.h"
 #include "ngx_js_shared_dict.h"
 
@@ -2005,14 +2007,16 @@ ngx_js_render_string(njs_chb_t *chain, ngx_str_t *str)
 static ngx_int_t
 ngx_js_dict_render_json(ngx_js_dict_t *dict, njs_chb_t *chain)
 {
+    int                  flags;
     u_char              *p, *dst;
     size_t               len;
-    ngx_uint_t           first;
+    ngx_uint_t           first, quote;
     ngx_msec_t           now;
     ngx_time_t          *tp;
     ngx_rbtree_t        *rbtree;
     ngx_rbtree_node_t   *rn, *next;
     ngx_js_dict_node_t  *node;
+    JSDTOATempMem        tmp_mem;
 
     tp = ngx_timeofday();
     now = tp->sec * 1000 + tp->msec;
@@ -2027,6 +2031,7 @@ ngx_js_dict_render_json(ngx_js_dict_t *dict, njs_chb_t *chain)
     }
 
     first = 1;
+    flags = JS_DTOA_FORMAT_FREE | JS_DTOA_MINUS_ZERO;
 
     for (rn = ngx_rbtree_min(rbtree->root, rbtree->sentinel);
          rn != NULL;
@@ -2060,15 +2065,26 @@ ngx_js_dict_render_json(ngx_js_dict_t *dict, njs_chb_t *chain)
             }
 
         } else {
-            len = sizeof("\"value\":.") + 18 + 6;
+            njs_chb_append_literal(chain, "\"value\":");
+
+            quote = !isfinite(node->value.number);
+            if (quote) {
+                njs_chb_append_literal(chain, "\"");
+            }
+
+            len = njs_dtoa_max_len(node->value.number, 10, 0, flags);
             dst = njs_chb_reserve(chain, len);
             if (dst == NULL) {
                 return NGX_ERROR;
             }
 
-            p = njs_sprintf(dst, dst + len, "\"value\":%.6f",
-                            node->value.number);
-            njs_chb_written(chain, p - dst);
+            len = njs_dtoa2((char *) dst, node->value.number, 10, 0, flags,
+                            &tmp_mem);
+            njs_chb_written(chain, len);
+
+            if (quote) {
+                njs_chb_append_literal(chain, "\"");
+            }
         }
 
         if (dict->timeout) {
@@ -2410,19 +2426,36 @@ ngx_js_dict_parse_entry(ngx_js_dict_t *dict, ngx_pool_t *pool,
             }
 
             if (key.len == 5 && ngx_strncmp(key.data, "value", 5) == 0) {
-                if (dict->type != NGX_JS_DICT_TYPE_STRING) {
-                    *err = "expected string value";
+                if (dict->type == NGX_JS_DICT_TYPE_STRING) {
+                    entry->value.str = str;
+
+                } else if (str.len == 3
+                           && ngx_strncmp(str.data, "NaN", 3) == 0)
+                {
+                    entry->value.number = NAN;
+
+                } else if (str.len == 8
+                           && ngx_strncmp(str.data, "Infinity", 8) == 0)
+                {
+                    entry->value.number = INFINITY;
+
+                } else if (str.len == 9
+                           && ngx_strncmp(str.data, "-Infinity", 9) == 0)
+                {
+                    entry->value.number = -INFINITY;
+
+                } else {
+                    *err = "expected number value";
                     goto error;
                 }
 
-                entry->value.str = str;
                 see_value = 1;
             }
 
         } else {
             pp = p;
             number = strtod((char *) p, (char **) &p);
-            if (pp == p) {
+            if (pp == p || !isfinite(number)) {
                 *err = "invalid number value";
                 goto error;
             }
diff --git a/nginx/t/js_shared_dict_state_numbers.t b/nginx/t/js_shared_dict_state_numbers.t
new file mode 100644 (file)
index 0000000..cec59ef
--- /dev/null
@@ -0,0 +1,117 @@
+#!/usr/bin/perl
+
+# (C) Dmitry Volyntsev
+# (C) F5, Inc.
+
+# Tests for exact shared dictionary number persistence.
+
+use warnings;
+use strict;
+use Test::More;
+
+BEGIN { use FindBin; chdir($FindBin::Bin); }
+use lib 'lib';
+use Test::Nginx;
+use Test::Nginx::Stream qw/stream/;
+use JSON::PP;
+
+my $t = Test::Nginx->new()->has(qw/http stream/)
+    ->write_file_expand('nginx.conf', <<'EOF');
+
+%%TEST_GLOBALS%%
+daemon off;
+events {}
+
+http {
+    %%TEST_GLOBALS_HTTP%%
+    js_import test.js;
+    js_shared_dict_zone zone=http_nums:512k type=number state=http.json;
+
+    server {
+        listen 127.0.0.1:8080;
+        location /fill { js_content test.http_fill; }
+        location /check { js_content test.http_check; }
+    }
+}
+
+stream {
+    %%TEST_GLOBALS_STREAM%%
+    js_import test.js;
+    js_shared_dict_zone zone=stream_nums:512k type=number state=stream.json;
+    js_set $fill test.fill;
+    js_set $check test.check;
+
+    server {
+        listen 127.0.0.1:8081;
+        return $fill;
+    }
+    server {
+        listen 127.0.0.1:8082;
+        return $check;
+    }
+}
+EOF
+
+$t->write_file('test.js', <<'EOF');
+    const values = {zero: 0, negative_zero: -0, fraction: 0.1,
+        pi: Math.PI, tiny: 1e-7, minimum: Number.MIN_VALUE,
+        maximum: Number.MAX_VALUE, integer: Number.MAX_SAFE_INTEGER,
+        nan: NaN, infinity: Infinity, negative_infinity: -Infinity};
+
+    function fill(s) {
+        const d = ngx.shared[s ? 'stream_nums' : 'http_nums'];
+        Object.keys(values).forEach(key => d.set(key, values[key]));
+        d.incr('overflow', Number.MAX_VALUE, Number.MAX_VALUE);
+        return 'filled';
+    }
+
+    function check(s) {
+        const d = ngx.shared[s ? 'stream_nums' : 'http_nums'];
+        const results = Object.keys(values).map(key => ({key,
+            ok: Object.is(d.get(key), values[key]),
+            value: String(d.get(key))}));
+        results.push({key: 'overflow', ok: d.get('overflow') === Infinity,
+            value: String(d.get('overflow'))});
+        return JSON.stringify(results);
+    }
+
+    function http_fill(r) { r.return(200, fill()); }
+    function http_check(r) { r.return(200, check()); }
+    export default {fill, check, http_fill, http_check};
+EOF
+
+$t->run()->plan(50);
+
+http_get('/fill');
+stream('127.0.0.1:' . port(8081))->read();
+check_values('before restart');
+
+$t->stop();
+
+for my $file ('http.json', 'stream.json') {
+    my $state = $t->read_file($file);
+    my $valid = eval { JSON::PP::decode_json($state); 1 };
+    ok($valid, "$file is valid JSON") or diag($state);
+}
+
+$t->run();
+check_values('after restart');
+
+sub check_values {
+    my ($phase) = @_;
+    my ($http) = http_get('/check') =~ /\x0d\x0a\x0d\x0a(.*)/s;
+    my $connection = stream('127.0.0.1:' . port(8082));
+    my $stream = '';
+    my $chunk;
+    while (defined($chunk = $connection->read()) && length($chunk)) {
+        $stream .= $chunk;
+    }
+
+    for my $response (['http', $http], ['stream', $stream]) {
+        my $results = JSON::PP::decode_json($response->[1]);
+        for my $result (@$results) {
+            ok($result->{ok}, "$response->[0] $result->{key} $phase")
+                or diag(JSON::PP::encode_json($result));
+        }
+    }
+}