Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON: support basic legacy path #1829

Open
wants to merge 13 commits into
base: unstable
Choose a base branch
from
5 changes: 4 additions & 1 deletion src/commands/cmd_json.cc
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@

namespace redis {

///
/// JSON.SET <key> <path> <json>
///
class CommandJsonSet : public Commander {
public:
Status Execute(Server *svr, Connection *conn, std::string *output) override {
Expand Down Expand Up @@ -52,7 +55,7 @@ class CommandJsonGet : public Commander {
}
};

REDIS_REGISTER_COMMANDS(MakeCmdAttr<CommandJsonSet>("json.set", -3, "write", 1, 1, 1),
REDIS_REGISTER_COMMANDS(MakeCmdAttr<CommandJsonSet>("json.set", 4, "write", 1, 1, 1),
MakeCmdAttr<CommandJsonGet>("json.get", -2, "read-only", 1, 1, 1), );

} // namespace redis
25 changes: 20 additions & 5 deletions src/types/json.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include <jsoncons/json_error.hpp>
#include <jsoncons_ext/jsonpath/json_query.hpp>

#include "json_path.h"
#include "jsoncons_ext/jsonpath/jsonpath_error.hpp"
#include "status.h"

Expand Down Expand Up @@ -54,20 +55,34 @@ struct JsonValue {
}

Status Set(std::string_view path, JsonValue &&new_value) {
auto path_express_status = JsonPath::BuildJsonPath(path);
if (!path_express_status) {
return path_express_status.ToStatus();
}
return Set(path_express_status.GetValue(), std::move(new_value));
}
mapleFU marked this conversation as resolved.
Show resolved Hide resolved

Status Set(const JsonPath &path, JsonValue &&new_value) {
try {
jsoncons::jsonpath::json_replace(value, path, [&new_value](const std::string & /*path*/, jsoncons::json &origin) {
origin = new_value.value;
});
path.EvalReplaceExpression(
Copy link
Member

Choose a reason for hiding this comment

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

Actually I do not think this function name is clear enough. Maybe we can figure out another name.

value, [&new_value](const std::string_view & /*path*/, jsoncons::json &origin) { origin = new_value.value; });
} catch (const jsoncons::jsonpath::jsonpath_error &e) {
return {Status::NotOK, e.what()};
}

return Status::OK();
}

StatusOr<JsonValue> Get(std::string_view path) const {
auto path_express_status = JsonPath::BuildJsonPath(path);
if (!path_express_status) {
return path_express_status.ToStatus();
}
return Get(path_express_status.GetValue());
mapleFU marked this conversation as resolved.
Show resolved Hide resolved
}

StatusOr<JsonValue> Get(const JsonPath &json_path) const {
try {
return jsoncons::jsonpath::json_query(value, path);
return json_path.EvalQueryExpression(value);
} catch (const jsoncons::jsonpath::jsonpath_error &e) {
return {Status::NotOK, e.what()};
}
Expand Down
65 changes: 65 additions & 0 deletions src/types/json_path.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
mapleFU marked this conversation as resolved.
Show resolved Hide resolved
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/

#include "json_path.h"

StatusOr<JsonPath> JsonPath::BuildJsonPath(std::string_view path) {
std::string fixed_path;
std::string_view json_string;
auto converted = tryConvertLegacyToJsonPath(path);
if (converted.has_value()) {
fixed_path = std::move(converted.value());
}
if (fixed_path.empty()) {
json_string = path;
} else {
json_string = fixed_path;
}

std::error_code json_parse_error;
auto path_expression = jsoncons::jsonpath::make_expression<JsonType>(json_string, json_parse_error);
if (json_parse_error) {
return {Status::NotOK, json_parse_error.message()};
}
return JsonPath(std::string(path), std::move(fixed_path), std::move(path_expression));
}

// https://redis.io/docs/data-types/json/path/#legacy-path-syntax
// The logic here is port from RedisJson `Path::new`.
mapleFU marked this conversation as resolved.
Show resolved Hide resolved
std::optional<std::string> JsonPath::tryConvertLegacyToJsonPath(std::string_view path) {
if (path.empty()) {
return std::nullopt;
}
if (path[0] == '$') {
if (path.size() == 1) {
return std::nullopt;
}
if (path[1] == '.' || path[1] == '[') {
return std::nullopt;
}
}
if (path[0] == '.') {
if (path.size() == 1) {
return "$";
}
return std::string("$") + std::string(path);
}
return std::string("$.") + std::string(path);
}
77 changes: 77 additions & 0 deletions src/types/json_path.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/

#pragma once

#include <jsoncons_ext/jsonpath/jsonpath.hpp>
#include <jsoncons_ext/jsonpath/jsonpath_error.hpp>

#include "jsoncons_ext/jsonpath/jsonpath_error.hpp"
#include "status.h"

class JsonPath {
public:
using JsonType = jsoncons::basic_json<char>;
mapleFU marked this conversation as resolved.
Show resolved Hide resolved
using JsonPathExpression = jsoncons::jsonpath::jsonpath_expression<JsonType, const JsonType&>;
using JsonQueryCallback = std::function<void(const std::string_view&, const JsonType&)>;
Copy link
Member

Choose a reason for hiding this comment

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

Cannot find where it is used 🤔

Copy link
Member Author

Choose a reason for hiding this comment

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

Remove it

using JsonReplaceCallback = std::function<void(const std::string_view&, JsonType&)>;

static constexpr std::string_view ROOT_PATH = "$";

static StatusOr<JsonPath> BuildJsonPath(std::string_view path);
static JsonPath BuildJsonRootPath() { return BuildJsonPath(std::string(ROOT_PATH)).GetValue(); }
mapleFU marked this conversation as resolved.
Show resolved Hide resolved

bool IsLegacy() const noexcept { return !fixed_path_.empty(); }

std::string_view Path() const {
if (IsLegacy()) {
return fixed_path_;
}
return origin_;
}

std::string_view OriginPath() const { return origin_; }

bool IsRootPath() const { return Path() == ROOT_PATH; }

JsonType EvalQueryExpression(const JsonType& json_value) const {
return expression_.evaluate(const_cast<JsonType&>(json_value));
}

void EvalReplaceExpression(JsonType& json_value, const JsonReplaceCallback& callback) const {
auto wrapped_cb = [&callback](const std::string_view& path, const JsonType& json) {
// Though JsonPath supports mutable reference, `jsoncons::make_expression`
// only supports const reference, so const_cast is used as a workaround.
callback(path, const_cast<JsonType&>(json));
};
expression_.evaluate(json_value, wrapped_cb);
}
Copy link
Member

Choose a reason for hiding this comment

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

Is it necessary to provide two function?

Copy link
Member Author

Choose a reason for hiding this comment

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

🤔the first one is used to get a JsonValue, the second value is used to replace. Any better idea for this?


private:
static std::optional<std::string> tryConvertLegacyToJsonPath(std::string_view path);

JsonPath(std::string path, std::string fixed_path, JsonPathExpression path_expression)
: origin_(std::move(path)), fixed_path_(std::move(fixed_path)), expression_(std::move(path_expression)) {}

std::string origin_;
Copy link
Member

Choose a reason for hiding this comment

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

Is it necessary to store the original path string? Or just store the original one rather than the modified one?

Copy link
Member Author

Choose a reason for hiding this comment

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

Is it necessary to store the original path string

We need the OriginPath in someplace like MSET. It's also ok to only has the origin_path and expression. But I think it would not heavy to having one more string?

std::string fixed_path_;
// Pre-build the expression to avoid built it multiple times.
JsonPathExpression expression_;
};
21 changes: 16 additions & 5 deletions src/types/redis_json.cc
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#include "redis_json.h"

#include "json.h"
#include "json_path.h"
#include "lock_manager.h"
#include "storage/redis_metadata.h"

Expand Down Expand Up @@ -52,8 +53,14 @@ rocksdb::Status Json::Set(const std::string &user_key, const std::string &path,
Slice rest;
auto s = GetMetadata(kRedisJson, ns_key, &bytes, &metadata, &rest);

auto json_path_opt = JsonPath::BuildJsonPath(path);
if (!json_path_opt) {
return rocksdb::Status::InvalidArgument(json_path_opt.Msg());
}
const auto &json_path = json_path_opt.GetValue();

if (s.IsNotFound()) {
if (path != "$") return rocksdb::Status::InvalidArgument("new objects must be created at the root");
if (!json_path.IsRootPath()) return rocksdb::Status::InvalidArgument("new objects must be created at the root");

auto json_res = JsonValue::FromString(value);
if (!json_res) return rocksdb::Status::InvalidArgument(json_res.Msg());
Expand All @@ -75,7 +82,7 @@ rocksdb::Status Json::Set(const std::string &user_key, const std::string &path,
if (!origin_res) return rocksdb::Status::Corruption(origin_res.Msg());
auto origin = *std::move(origin_res);

auto set_res = origin.Set(path, std::move(new_val));
auto set_res = origin.Set(json_path, std::move(new_val));
if (!set_res) return rocksdb::Status::InvalidArgument(set_res.Msg());

return write(ns_key, &metadata, origin);
Expand All @@ -102,14 +109,18 @@ rocksdb::Status Json::Get(const std::string &user_key, const std::vector<std::st
if (paths.empty()) {
res = std::move(json_val);
} else if (paths.size() == 1) {
auto get_res = json_val.Get(paths[0]);
auto json_path_result = JsonPath::BuildJsonPath(paths[0]);
if (!json_path_result) return rocksdb::Status::InvalidArgument(json_path_result.Msg());
auto get_res = json_val.Get(json_path_result.GetValue());
if (!get_res) return rocksdb::Status::InvalidArgument(get_res.Msg());
res = *std::move(get_res);
} else {
for (const auto &path : paths) {
auto get_res = json_val.Get(path);
auto json_path_result = JsonPath::BuildJsonPath(path);
if (!json_path_result) return rocksdb::Status::InvalidArgument(json_path_result.Msg());
auto get_res = json_val.Get(json_path_result.GetValue());
if (!get_res) return rocksdb::Status::InvalidArgument(get_res.Msg());
mapleFU marked this conversation as resolved.
Show resolved Hide resolved
res.value.insert_or_assign(path, std::move(get_res->value));
res.value.insert_or_assign(json_path_result->OriginPath(), std::move(get_res->value));
}
}

Expand Down
18 changes: 18 additions & 0 deletions tests/cppunit/types/json_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,21 @@ TEST_F(RedisJsonTest, Get) {
ASSERT_TRUE(json_->Get(key_, {"$..x", "$..y", "$..z"}, &json_val_).ok());
ASSERT_EQ(json_val_.Dump(), R"({"$..x":[{"y":1},4],"$..y":[[2,{"z":3}],1],"$..z":[{"a":{"x":4}},3]})");
}

TEST_F(RedisJsonTest, LegacyPath) {
ASSERT_THAT(json_->Set(key_, ".", "invalid").ToString(), MatchesRegex(".*syntax_error.*"));
ASSERT_THAT(json_->Set(key_, ".", "{").ToString(), MatchesRegex(".*Unexpected end of file.*"));

ASSERT_TRUE(json_->Set(key_, ".", " \t{\n } ").ok());
ASSERT_TRUE(json_->Get(key_, {"."}, &json_val_).ok());
ASSERT_EQ(json_val_.Dump(), "[{}]");

auto s = json_->Set(key_, ".", "1");
ASSERT_TRUE(s.ok()) << s.ToString();
ASSERT_TRUE(json_->Get(key_, {"."}, &json_val_).ok());
ASSERT_EQ(json_val_.Dump(), "[1]");

ASSERT_TRUE(json_->Set(key_, ".", "[1, 2, 3]").ok());
ASSERT_TRUE(json_->Get(key_, {"."}, &json_val_).ok());
ASSERT_EQ(json_val_.Dump(), "[[1,2,3]]");
mapleFU marked this conversation as resolved.
Show resolved Hide resolved
}