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
29 changes: 18 additions & 11 deletions src/ivalue_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,12 @@ use redis_module::{Context, NotifyEvent, RedisString};
use serde::Serialize;
use serde_json::Number;
use std::marker::PhantomData;
use std::mem::size_of;

use crate::redisjson::RedisJSON;

use crate::array_index::ArrayIndex;

use std::mem;

use bson::decode_document;
use std::io::Cursor;

Expand Down Expand Up @@ -628,15 +627,23 @@ impl<'a> Manager for RedisIValueJsonKeyManager<'a> {
}

fn get_memory(&self, v: &Self::V) -> Result<usize, RedisError> {
// todo: implement
let res = match v.type_() {
ValueType::Null => 0,
ValueType::Bool => mem::size_of_val(v),
ValueType::Number => mem::size_of_val(v),
ValueType::String => mem::size_of_val(v),
ValueType::Array => mem::size_of_val(v),
ValueType::Object => mem::size_of_val(v),
};
let res = size_of::<IValue>()
+ match v.type_() {
ValueType::Null | ValueType::Bool | ValueType::Number => 0,
ValueType::String => v.as_string().unwrap().len(),
ValueType::Array => v
.as_array()
.unwrap()
.into_iter()
.map(|v| self.get_memory(v).unwrap())
Comment thread
gkorland marked this conversation as resolved.
Resolved
.sum(),
ValueType::Object => v
.as_object()
.unwrap()
.into_iter()
.map(|(s, v)| s.len() + self.get_memory(v).unwrap())
Comment thread
gkorland marked this conversation as resolved.
Resolved
.sum(),
};
Ok(res)
}

Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub static REDIS_JSON_TYPE: RedisType = RedisType::new(
free: Some(redisjson::type_methods::free),

// Currently unused by Redis
mem_usage: None,
mem_usage: Some(redisjson::type_methods::mem_usage),
digest: None,

// Auxiliary data (v2)
Expand Down
20 changes: 20 additions & 0 deletions src/redisjson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,4 +223,24 @@ pub mod type_methods {
};
raw::save_string(rdb, &json);
}

#[allow(non_snake_case, unused)]
pub unsafe extern "C" fn mem_usage(value: *const c_void) -> usize {
match get_manager_type() {
ManagerType::SerdeValue => {
let json = unsafe { &*(value as *mut RedisJSON<serde_json::Value>) };
let manager = RedisJsonKeyManager {
phantom: PhantomData,
};
manager.get_memory(&json.data).unwrap_or(0)
}
ManagerType::IValue => {
let json = unsafe { &*(value as *mut RedisJSON<ijson::IValue>) };
let manager = RedisIValueJsonKeyManager {
phantom: PhantomData,
};
manager.get_memory(&json.data).unwrap_or(0)
}
}
}
}
31 changes: 30 additions & 1 deletion tests/pytest/common.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import signal
from contextlib import contextmanager

from functools import wraps
from includes import *

@contextmanager
def TimeLimit(timeout):
Expand All @@ -14,3 +15,31 @@ def handler(signum, frame):
finally:
signal.setitimer(signal.ITIMER_REAL, 0)
signal.signal(signal.SIGALRM, signal.SIG_DFL)

def skipOnExistingEnv(env):
if 'existing' in env.env:
env.skip()

def skipOnCrdtEnv(env):
if len([a for a in env.cmd('module', 'list') if a[1] == 'crdt']) > 0:
env.skip()

def skip(f, on_cluster=False):
@wraps(f)
def wrapper(env, *args, **kwargs):
if not on_cluster or env.isCluster():
env.skip()
return
return f(env, *args, **kwargs)
return wrapper

def no_san(f):
@wraps(f)
def wrapper(env, *args, **kwargs):
if SANITIZER != '':
fname = f.__name__
env.debugPrint("skipping {} due to sanitizer".format(fname), force=True)
env.skip()
return
return f(env, *args, **kwargs)
return wrapper
7 changes: 7 additions & 0 deletions tests/pytest/includes.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,10 @@
import paella
except:
pass

ONLY_STABLE = os.getenv('ONLY_STABLE', '0') == '1'
SANITIZER = os.getenv('SANITIZER', '')
VALGRIND = os.getenv('VALGRIND', '0') == '1'
CODE_COVERAGE = os.getenv('CODE_COVERAGE', '0') == '1'

OSNICK = paella.Platform().osnick
45 changes: 36 additions & 9 deletions tests/pytest/test_multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import redis
import json
from RLTest import Env

from common import *
from includes import *

from RLTest import Defaults
Expand Down Expand Up @@ -766,7 +768,6 @@ def testClearCommand(env):
r.expect('JSON.CLEAR', 'non_existing_doc', '$..a').raiseError()



def testToggleCommand(env):
"""
Test REJSON.TOGGLE command
Expand All @@ -789,33 +790,59 @@ def testToggleCommand(env):
# Test missing key
r.expect('JSON.TOGGLE', 'non_existing_doc', '$..a').raiseError()

@no_san
Comment thread
gkorland marked this conversation as resolved.
Resolved
def testMemoryUsage(env):
"""
Test MEMORY USAGE key
"""
if env.moduleArgs is not None and ['JSON_BACKEND SERDE_JSON'] in env.moduleArgs:
env.skip()

env

r = env
jdata, jtypes = load_types_data('a')
r.assertOk(r.execute_command('JSON.SET', 'doc1', '$', json.dumps(jdata)))
res = r.execute_command('MEMORY', 'USAGE', 'doc1')
r.assertEqual(res, 211)

jdata, jtypes = load_types_data('verylongfieldname')
r.assertOk(r.execute_command('JSON.SET', 'doc2', '$', json.dumps(jdata)))
res = r.execute_command('MEMORY', 'USAGE', 'doc2')
r.assertEqual(res, 323)

@no_san
def testDebugCommand(env):
"""
Test REJSON.DEBUG MEMORY command
"""
env.skip() # test is currently irrelevant as the number are not correct, todo: re-enable once fixing the json.debug memory command
Test REJSON.DEBUG MEMORY command
"""
if env.moduleArgs is not None and ['JSON_BACKEND SERDE_JSON'] in env.moduleArgs:
env.skip()

r = env
jdata, jtypes = load_types_data('a')

r.assertOk(r.execute_command('JSON.SET', 'doc1', '$', json.dumps(jdata)))

# Test multi
# json.get a $..a ==> "[{},[],\"str\",42,1.2,false,null]"
res = r.execute_command('JSON.DEBUG', 'MEMORY', 'doc1', '$..a')
r.assertEqual(res, [72, 24, 24, 16, 16, 1, 0])
r.assertEqual(res, [8, 8, 11, 8, 8, 8, 8])

# Test single
res = r.execute_command('JSON.DEBUG', 'MEMORY', 'doc1', '$.nested2.a')
r.assertEqual(res, [24])
r.assertEqual(res, [8])

# Test legacy
res = r.execute_command('JSON.DEBUG', 'MEMORY', 'doc1', '..a')
r.assertEqual(res, 72)
r.assertEqual(res, 8)
# Test missing path (defaults to root)
res = r.execute_command('JSON.DEBUG', 'MEMORY', 'doc1')
r.assertEqual(res, 72)
r.assertEqual(res, 179)
Comment thread
gkorland marked this conversation as resolved.
Resolved

# Test missing subcommand
r.expect('JSON.DEBUG', 'non_existing_doc', '$..a').raiseError()


def testRespCommand(env):
"""Test REJSON.RESP command"""
r = env
Expand Down
2 changes: 2 additions & 0 deletions tests/pytest/tests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ setup_redis_server() {

export ASAN_OPTIONS=detect_odr_violation=0
# :detect_leaks=0
# for RLTest
export SANITIZER="$SAN"

elif [[ $SAN == mem || $SAN == memory ]]; then
REDIS_SERVER=${REDIS_SERVER:-redis-server-msan-6.2}
Expand Down