Skip to content

Split JsonMessageCodec out from JsonMethodCodec #150

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

Merged
merged 2 commits into from
Nov 14, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
#ifndef LIBRARY_LINUX_INCLUDE_FLUTTER_DESKTOP_EMBEDDING_JSON_METHOD_CODEC_H_
#define LIBRARY_LINUX_INCLUDE_FLUTTER_DESKTOP_EMBEDDING_JSON_METHOD_CODEC_H_

#include <json/json.h>

#include "method_codec.h"

namespace flutter_desktop_embedding {
Expand Down Expand Up @@ -49,11 +47,6 @@ class JsonMethodCodec : public MethodCodec {
std::unique_ptr<std::vector<uint8_t>> EncodeErrorEnvelopeInternal(
const std::string &error_code, const std::string &error_message,
const void *error_details) const override;

private:
// Serializes |json| into a byte stream.
std::unique_ptr<std::vector<uint8_t>> EncodeJsonObject(
const Json::Value &json) const;
};

} // namespace flutter_desktop_embedding
Expand Down
55 changes: 55 additions & 0 deletions library/linux/src/internal/json_message_codec.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright 2018 Google LLC
//
// Licensed 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 "library/linux/src/internal/json_message_codec.h"

#include <iostream>
#include <string>

namespace flutter_desktop_embedding {

// static
const JsonMessageCodec &JsonMessageCodec::GetInstance() {
static JsonMessageCodec sInstance;
return sInstance;
}

std::unique_ptr<std::vector<uint8_t>> JsonMessageCodec::EncodeMessage(
const Json::Value &message) const {
Json::StreamWriterBuilder writer_builder;
std::string serialization = Json::writeString(writer_builder, message);

return std::make_unique<std::vector<uint8_t>>(serialization.begin(),
serialization.end());
}

std::unique_ptr<Json::Value> JsonMessageCodec::DecodeMessage(
const uint8_t *message, const size_t message_size) const {
Json::CharReaderBuilder reader_builder;
std::unique_ptr<Json::CharReader> parser(reader_builder.newCharReader());

auto raw_message = reinterpret_cast<const char *>(message);
auto json_message = std::make_unique<Json::Value>();
std::string parse_errors;
bool parsing_successful =
parser->parse(raw_message, raw_message + message_size, json_message.get(),
&parse_errors);
if (!parsing_successful) {
std::cerr << "Unable to parse JSON message:" << std::endl
<< parse_errors << std::endl;
return nullptr;
}
return json_message;
}

} // namespace flutter_desktop_embedding
59 changes: 59 additions & 0 deletions library/linux/src/internal/json_message_codec.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright 2018 Google LLC
//
// Licensed 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.
#ifndef LIBRARY_LINUX_INCLUDE_FLUTTER_DESKTOP_EMBEDDING_JSON_MESSAGE_CODEC_H_
#define LIBRARY_LINUX_INCLUDE_FLUTTER_DESKTOP_EMBEDDING_JSON_MESSAGE_CODEC_H_

#include <memory>
#include <vector>

#include <json/json.h>

namespace flutter_desktop_embedding {

// A message encoding/decoding mechanism for communications to/from the
// Flutter engine via JSON channels.
//
// TODO: Make this public, once generalizing a MessageCodec parent interface is
// addressed; this is complicated by the return type of EncodeMessage.
// Part of issue #102.
class JsonMessageCodec {
public:
// Returns the shared instance of the codec.
static const JsonMessageCodec &GetInstance();

~JsonMessageCodec() = default;

// Prevent copying.
JsonMessageCodec(JsonMessageCodec const &) = delete;
JsonMessageCodec &operator=(JsonMessageCodec const &) = delete;

// Returns a binary encoding of the given message, or nullptr if the
// message cannot be serialized by this codec.
std::unique_ptr<std::vector<uint8_t>> EncodeMessage(
const Json::Value &message) const;

// Returns the MethodCall encoded in |message|, or nullptr if it cannot be
Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe I'm misunderstanding this comment, but it looks like MethodCodec is taking responsibility for this (getting the MethodCall encoded in a |message|), and that MessageCodec is just here to verify and decode that some kind of valid JSON message was received, not necessarily anything adhering to a specific protocol.

To me this implies that there's some more specific checking/verification happening within this method before returning the final Json::Value.

If it is the case that this is supposed to be more general, I might also ask that beyond updating this comment, to update the class header as well. It seems this is just a generally JSON message decoder rather than one that verifies any codec.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Sorry, this was a copypasta. It should have been s/MethodCall/message/. I'll fix and re-upload tomorrow.

For more context, the Flutter APIs that I'm moving toward following have:

  • MessageChannel: A named channel for communicating between Flutter and platform code. A MessageChannel has a specific codec associated with it at creation (JSON, Standard, etc.) but beyond that doesn't have any expectations about the contents, so clients can define whatever structure they want.
  • MethodChannel: A layer on top of MessageChannel which adds a few expectations about structure: the incoming message should have a method name and optional arguments, and there should be a response that communicates success/error/not-implemented using a defined structure.

The Codec family of classes has the same split, with the MethodCodec family knowing about encoding/decoding that added layer of structure.

Our existing Plugin API doesn't have this distinction, because everything we built it to interface with so far has used MethodChannel on the Flutter side. But we do want to support it in general as part of the API alignment I'm working on, and in particular it's relevant now because the raw key event handling code in Flutter uses MessageChannel rather than MethodChannel.

So this is a small step toward adding that separation in the desktop APIs as well.

If it is the case that this is supposed to be more general, I might also ask that beyond updating this comment, to update the class header as well. It seems this is just a generally JSON message decoder rather than one that verifies any codec.

In the Flutter API terminology, a (Message)Codec is just an encoder/decoder. It's not until you get to the MethodCodec layer that there's an assumed structure beyond how different data types are represented. I could make the class comment slightly more generic by removing the reference to channels, but the reason the Codec classes exist as an API is for use by channels; if someone wanted to do JSON encoding/decoding for reasons other than channel messages they should just use an existing JSON API (e.g., jsoncpp) directly.

// decoded.
// TODO: Consider adding absl as a dependency and using absl::Span.
std::unique_ptr<Json::Value> DecodeMessage(const uint8_t *message,
const size_t message_size) const;

protected:
// Instances should be obtained via GetInstance.
JsonMessageCodec() = default;
};

} // namespace flutter_desktop_embedding

#endif // LIBRARY_LINUX_INCLUDE_FLUTTER_DESKTOP_EMBEDDING_JSON_MESSAGE_CODEC_H_
36 changes: 9 additions & 27 deletions library/linux/src/json_method_codec.cc
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@
// limitations under the License.
#include "library/linux/include/flutter_desktop_embedding/json_method_codec.h"

#include <iostream>

#include "library/linux/include/flutter_desktop_embedding/json_method_call.h"
#include "library/linux/src/internal/json_message_codec.h"

namespace flutter_desktop_embedding {

Expand All @@ -33,25 +32,17 @@ const JsonMethodCodec &JsonMethodCodec::GetInstance() {

std::unique_ptr<MethodCall> JsonMethodCodec::DecodeMethodCallInternal(
const uint8_t *message, const size_t message_size) const {
Json::CharReaderBuilder reader_builder;
std::unique_ptr<Json::CharReader> parser(reader_builder.newCharReader());

auto raw_message = reinterpret_cast<const char *>(message);
Json::Value json_message;
std::string parse_errors;
bool parsing_successful = parser->parse(
raw_message, raw_message + message_size, &json_message, &parse_errors);
if (!parsing_successful) {
std::cerr << "Unable to parse JSON method call:" << std::endl
<< parse_errors << std::endl;
std::unique_ptr<Json::Value> json_message =
JsonMessageCodec::GetInstance().DecodeMessage(message, message_size);
if (!json_message) {
return nullptr;
}

Json::Value method = json_message[kMessageMethodKey];
Json::Value method = (*json_message)[kMessageMethodKey];
if (method.isNull()) {
return nullptr;
}
Json::Value arguments = json_message[kMessageArgumentsKey];
Json::Value arguments = (*json_message)[kMessageArgumentsKey];
return std::make_unique<JsonMethodCall>(method.asString(), arguments);
}

Expand All @@ -62,7 +53,7 @@ std::unique_ptr<std::vector<uint8_t>> JsonMethodCodec::EncodeMethodCallInternal(
message[kMessageArgumentsKey] =
*static_cast<const Json::Value *>(method_call.arguments());

return EncodeJsonObject(message);
return JsonMessageCodec::GetInstance().EncodeMessage(message);
}

std::unique_ptr<std::vector<uint8_t>>
Expand All @@ -71,7 +62,7 @@ JsonMethodCodec::EncodeSuccessEnvelopeInternal(const void *result) const {
envelope.append(result == nullptr
? Json::Value()
: *static_cast<const Json::Value *>(result));
return EncodeJsonObject(envelope);
return JsonMessageCodec::GetInstance().EncodeMessage(envelope);
}

std::unique_ptr<std::vector<uint8_t>>
Expand All @@ -84,16 +75,7 @@ JsonMethodCodec::EncodeErrorEnvelopeInternal(const std::string &error_code,
envelope.append(error_details == nullptr
? Json::Value()
: *static_cast<const Json::Value *>(error_details));
return EncodeJsonObject(envelope);
}

std::unique_ptr<std::vector<uint8_t>> JsonMethodCodec::EncodeJsonObject(
const Json::Value &json) const {
Json::StreamWriterBuilder writer_builder;
std::string serialization = Json::writeString(writer_builder, json);

return std::make_unique<std::vector<uint8_t>>(serialization.begin(),
serialization.end());
return JsonMessageCodec::GetInstance().EncodeMessage(envelope);
}

} // namespace flutter_desktop_embedding