Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ on: [push]

jobs:
python-tests:
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
name: Python ${{ matrix.python-version }} - Django ${{ matrix.django-version }}
strategy:
fail-fast: false
Expand Down Expand Up @@ -47,7 +47,7 @@ jobs:

services:
redis:
image: redis:7.4.1
image: redis:8
ports: ["6379:6379"]

steps:
Expand Down
8 changes: 8 additions & 0 deletions dj_redis_panel/encoding_utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
from typing import Dict, List, Union


Expand Down Expand Up @@ -70,6 +71,13 @@ def decode_zset_list(self, values: List[tuple]) -> List[tuple]:
"""
return [(self.decode_value(member), score) for member, score in values]

def decode_re_json_rl(self, value: bytes) -> str:
"""
Decode a RedisJSON document into pretty-printed JSON text.
"""
# RedisJSON always returns UTF-8 JSON text, so the configured encoder doesn't apply
return json.dumps(json.loads(value), indent=2, ensure_ascii=False)

def encode_for_redis(self, value: str) -> Union[str, bytes]:
"""
Convert a decoded string back to the format expected by Redis.
Expand Down
28 changes: 27 additions & 1 deletion dj_redis_panel/redis_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,9 @@ def paginated_scan(
if key_type == "string":
raw_value = redis_conn.get(key)
size = len(raw_value) if raw_value else 0
elif key_type == "ReJSON-RL":
# MEMORY USAGE avoids fetching the whole document just to size it
size = redis_conn.memory_usage(key)
elif key_type == "list":
size = redis_conn.llen(key)
elif key_type == "set":
Expand Down Expand Up @@ -647,6 +650,9 @@ def cursor_paginated_scan(
if key_type == "string":
raw_value = redis_conn.get(key)
size = len(raw_value) if raw_value else 0
elif key_type == "ReJSON-RL":
# MEMORY USAGE avoids fetching the whole document just to size it
size = redis_conn.memory_usage(key)
elif key_type == "list":
size = redis_conn.llen(key)
elif key_type == "set":
Expand Down Expand Up @@ -755,6 +761,11 @@ def get_key_data(
raw_value = redis_conn.get(key_name)
key_value = decoder.decode_value(raw_value) or ""
key_size = len(raw_value) if raw_value else 0
elif key_type == "ReJSON-RL":
raw_value = redis_conn.execute_command("JSON.GET", key_name)
key_value = decoder.decode_re_json_rl(raw_value)
# Same measure as the key search list, which can't afford to fetch documents
key_size = redis_conn.memory_usage(key_name)
elif key_type == "list":
raw_values = redis_conn.lrange(key_name, 0, -1)
key_value = decoder.decode_list(raw_values)
Expand Down Expand Up @@ -905,7 +916,22 @@ def get_paginated_key_data(
)

return base_response

elif key_type == "ReJSON-RL":
raw_value = redis_conn.execute_command("JSON.GET", key_name)
key_value = decoder.decode_re_json_rl(raw_value)
# Same measure as the key search list, which can't afford to fetch documents
key_size = redis_conn.memory_usage(key_name)
base_response = {
"name": key_name,
"type": key_type,
"ttl": ttl if ttl > 0 else None,
"size": key_size,
"value": key_value,
"exists": True,
"error": None,
"is_paginated": False,
}
return base_response

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is sort of forcing the function to do something it wasn't designed to do.

elif key_type == "list":
key_size = redis_conn.llen(key_name)
elif key_type == "set":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ <h2 class="dcr-section-header__title">{% trans "Key Information" %}</h2>
<div class="dcr-dl__row">
<dt class="dcr-dl__label">{% trans "Size" %}</dt>
<dd class="dcr-dl__value">
{% if key_data.type == "string" %}
{% if key_data.type == "string" or key_data.type == "ReJSON-RL" %}
{{ key_data.size }} {% trans "bytes" %}
{% else %}
{{ key_data.size }} {% trans "elements" %}
Expand Down Expand Up @@ -156,6 +156,8 @@ <h2 class="dcr-section-header__title">{% trans "Key Value" %}</h2>
{% include "admin/dj_redis_panel/key_detail_value_zset.html" %}
{% elif key_data.type == "hash" %}
{% include "admin/dj_redis_panel/key_detail_value_hash.html" %}
{% elif key_data.type == "ReJSON-RL" %}
{% include "admin/dj_redis_panel/key_detail_value_re_json_rl.html" %}
{% else %}
<p class="dcr-text-muted">{% trans "Unsupported key type for display:" %} {{ key_data.type }}</p>
{% endif %}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{% load i18n %}
{# RedisJSON value display template (read-only) #}

<div class="dcr-code-viewer">
<div class="dcr-code-viewer__header">
<span class="dcr-code-viewer__label">&lt;&gt; {% trans "JSON Value" %}</span>
</div>
<pre>{{ key_data.value }}</pre>
</div>
<p class="dcr-text-muted dcr-text-sm">{% trans "Value editing is not supported for RedisJSON keys." %}</p>
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ <h3 class="dcr-data-table__title">
<span class="dcr-badge dcr-badge--info">{{ key_info.type|upper }}</span>
</td>
<td class="dcr-col--right">
{% if key_info.type == 'string' %}
{% if key_info.type == 'string' or key_info.type == 'ReJSON-RL' %}
{{ key_info.size }} {% trans "bytes" %}
{% else %}
{{ key_info.size }} {% trans "items" %}
Expand Down
18 changes: 9 additions & 9 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ services:

# Standalone Redis server
redis:
image: redis:7
image: redis:8
ports:
- "6379:6379"

Expand All @@ -36,7 +36,7 @@ services:
# Start with SSL: docker compose --profile all up -d

redis-node-0:
image: redis:7
image: redis:8
ports:
- "9000:6379"
- "17000:16379"
Expand All @@ -45,7 +45,7 @@ services:
- redis-cluster

redis-node-1:
image: redis:7
image: redis:8
ports:
- "9001:6379"
- "17001:16379"
Expand All @@ -54,7 +54,7 @@ services:
- redis-cluster

redis-node-2:
image: redis:7
image: redis:8
ports:
- "9002:6379"
- "17002:16379"
Expand All @@ -64,7 +64,7 @@ services:

# Cluster initialization (non-SSL)
redis-cluster-init:
image: redis:7
image: redis:8
depends_on:
- redis-node-0
- redis-node-1
Expand All @@ -85,7 +85,7 @@ services:
# Ports 9100-9102: non-SSL, 9110-9112: SSL

redis-node-0-ssl:
image: redis:7
image: redis:8
ports:
- "9100:6379"
- "9110:6380"
Expand All @@ -101,7 +101,7 @@ services:
- all

redis-node-1-ssl:
image: redis:7
image: redis:8
ports:
- "9101:6379"
- "9111:6380"
Expand All @@ -117,7 +117,7 @@ services:
- all

redis-node-2-ssl:
image: redis:7
image: redis:8
ports:
- "9102:6379"
- "9112:6380"
Expand All @@ -134,7 +134,7 @@ services:

# Cluster initialization (SSL)
redis-cluster-init-ssl:
image: redis:7
image: redis:8
depends_on:
- redis-node-0-ssl
- redis-node-1-ssl
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import json
import random
from datetime import datetime, timedelta
import redis.exceptions


class Command(BaseCommand):
Expand Down Expand Up @@ -150,22 +151,24 @@ def create_test_data(self, redis_conn, db_num, key_count=100, options=None):
options = {}

# Key type distribution (percentages)
string_ratio = 0.70 # 70% strings
string_ratio = 0.65 # 65% strings
json_ratio = 0.05 # 5% JSON (using json().set())
list_ratio = 0.10 # 10% lists
set_ratio = 0.08 # 8% sets
hash_ratio = 0.08 # 8% hashes
zset_ratio = 0.04 # 4% sorted sets

# Calculate counts for each type
string_count = int(key_count * string_ratio)
json_count = int(key_count * json_ratio)
list_count = int(key_count * list_ratio)
set_count = int(key_count * set_ratio)
hash_count = int(key_count * hash_ratio)
zset_count = int(key_count * zset_ratio)

# Lets add some string keys in case we are short on keys
total_allocated = sum(
[string_count, list_count, set_count, hash_count, zset_count]
[string_count, json_count, list_count, set_count, hash_count, zset_count]
)
if total_allocated < key_count:
string_count += key_count - total_allocated
Expand Down Expand Up @@ -283,6 +286,47 @@ def create_test_data(self, redis_conn, db_num, key_count=100, options=None):

created_keys += 1

# Create JSON keys using json().set()
json_keys_created = 0
for i in range(json_count):
json_key = f"json:data:{i}:db{db_num}"
json_value = {
"id": i,
"name": f"Item {i}",
"value": random.randint(1, 1000),
"active": random.choice([True, False]),
"metadata": {
"created_at": datetime.now().isoformat(),
"updated_at": (datetime.now() + timedelta(hours=random.randint(1, 24))).isoformat(),
"tags": [f"tag_{j}" for j in range(random.randint(1, 5))],
},
"nested": {
"field1": f"value_{random.randint(1, 100)}",
"field2": random.uniform(0.0, 100.0),
},
}
try:
redis_conn.json().set(json_key, "$", json_value)
json_keys_created += 1
created_keys += 1
except redis.exceptions.ResponseError as e:
# RedisJSON module not available, skip JSON keys
if "unknown command 'JSON.SET'" in str(e):
self.stdout.write(
self.style.WARNING(
" RedisJSON module not available, skipping JSON keys"
)
)
break
else:
self.stdout.write(
self.style.WARNING(f" Error creating JSON key: {e}")
)
except Exception as e:
self.stdout.write(
self.style.WARNING(f" Error creating JSON key: {e}")
)

# Create lists
for i in range(list_count):
list_key = f"list:queue:{i}:db{db_num}"
Expand Down Expand Up @@ -348,6 +392,8 @@ def create_test_data(self, redis_conn, db_num, key_count=100, options=None):
# Log what was created
self.stdout.write(f" Created {created_keys} total keys:")
self.stdout.write(f" - {string_count} string keys")
if json_keys_created > 0:
self.stdout.write(f" - {json_keys_created} JSON keys")
self.stdout.write(f" - {list_count} lists")
self.stdout.write(f" - {set_count} sets")
self.stdout.write(f" - {hash_count} hashes")
Expand Down
6 changes: 6 additions & 0 deletions tests/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,3 +317,9 @@ def get_key_value(self, key, db=15):
redis_host = os.environ.get("REDIS_HOST", "127.0.0.1")
conn = redis.Redis(host=redis_host, port=6379, db=db, decode_responses=True)
return conn.get(key)

def add_rejson_key(self, key, value, db=15):
"""Add a RedisJSON (ReJSON-RL) key. Requires Redis 8+."""
redis_host = os.environ.get("REDIS_HOST", "127.0.0.1")
conn = redis.Redis(host=redis_host, port=6379, db=db)
conn.json().set(key, "$", value)
24 changes: 24 additions & 0 deletions tests/test_key_detail.py
Original file line number Diff line number Diff line change
Expand Up @@ -619,3 +619,27 @@ def test_key_detail_pagination_template_includes(self):

finally:
self.redis_conn.delete(large_list_key)

def test_key_detail_shows_redisjson_value_as_pretty_printed_json(self):
self.add_rejson_key('test:json', {'name': 'Ada', 'tags': ['a', 'b']})

url = reverse('dj_redis_panel:key_detail', args=['test_redis', 15, 'test:json'])
response = self.client.get(url)

self.assertEqual(response.status_code, 200)
key_data = response.context['key_data']
self.assertEqual(key_data['type'], 'ReJSON-RL')
self.assertEqual(key_data['value'], '{\n "name": "Ada",\n "tags": [\n "a",\n "b"\n ]\n}')
self.assertContains(response, 'Value editing is not supported for RedisJSON keys.')

def test_key_detail_ttl_update_on_redisjson_key_keeps_showing_json(self):
self.add_rejson_key('test:json_ttl', {'name': 'Ada'})

url = reverse('dj_redis_panel:key_detail', args=['test_redis', 15, 'test:json_ttl'])
response = self.client.post(url, {'action': 'update_ttl', 'new_ttl': '600'})

self.assertEqual(response.context['success_message'], "TTL set to 600 seconds")
key_data = response.context['key_data']
self.assertEqual(key_data['type'], 'ReJSON-RL')
self.assertEqual(key_data['value'], '{\n "name": "Ada"\n}')
self.assertEqual(key_data['size'], self.redis_conn.memory_usage('test:json_ttl'))
28 changes: 28 additions & 0 deletions tests/test_key_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,34 @@ def test_key_search_pagination_navigation(self):
for i in range(50):
self.redis_conn.delete(f'pagination_test:{i}')

def test_key_search_lists_redisjson_key_with_same_size_as_detail_page(self):
self.add_rejson_key('search:json', {'name': 'Ada'})

search_url = reverse('dj_redis_panel:key_search', args=['test_redis', 15])
search_response = self.client.get(search_url, {'q': 'search:json'})
detail_url = reverse('dj_redis_panel:key_detail', args=['test_redis', 15, 'search:json'])
detail_response = self.client.get(detail_url)

keys_data = search_response.context['keys_data']
self.assertEqual(len(keys_data), 1)
self.assertEqual(keys_data[0]['type'], 'ReJSON-RL')
self.assertEqual(keys_data[0]['size'], detail_response.context['key_data']['size'])
self.assertContains(search_response, f"{keys_data[0]['size']} bytes")

def test_key_search_with_cursor_pagination_lists_redisjson_key(self):
self.add_rejson_key('cursor:json', {'name': 'Ada'}, db=14)
conn_14 = redis.Redis(host=os.environ.get('REDIS_HOST', '127.0.0.1'), port=6379, db=14)

try:
url = reverse('dj_redis_panel:key_search', args=['test_redis_no_features', 14])
response = self.client.get(url, {'cursor': '0', 'q': 'cursor:json'})

keys_data = response.context['keys_data']
self.assertEqual([key['type'] for key in keys_data], ['ReJSON-RL'])
self.assertGreater(keys_data[0]['size'], 0)
finally:
conn_14.flushdb()


class TestGetPageRange(RedisTestCase):
"""Test cases for the _get_page_range utility function."""
Expand Down
Loading