InspectorBackendDispatcher.cpp [plain text]
#include "config.h"
#include "InspectorBackendDispatcher.h"
#include "InspectorFrontendRouter.h"
#include <wtf/JSONValues.h>
#include <wtf/SetForScope.h>
#include <wtf/text/CString.h>
#include <wtf/text/WTFString.h>
namespace Inspector {
SupplementalBackendDispatcher::SupplementalBackendDispatcher(BackendDispatcher& backendDispatcher)
: m_backendDispatcher(backendDispatcher)
{
}
SupplementalBackendDispatcher::~SupplementalBackendDispatcher()
{
}
BackendDispatcher::CallbackBase::CallbackBase(Ref<BackendDispatcher>&& backendDispatcher, long requestId)
: m_backendDispatcher(WTFMove(backendDispatcher))
, m_requestId(requestId)
{
}
bool BackendDispatcher::CallbackBase::isActive() const
{
return !m_alreadySent && m_backendDispatcher->isActive();
}
void BackendDispatcher::CallbackBase::sendFailure(const ErrorString& error)
{
ASSERT(error.length());
if (m_alreadySent)
return;
m_alreadySent = true;
m_backendDispatcher->reportProtocolError(m_requestId, ServerError, error);
m_backendDispatcher->sendPendingErrors();
}
void BackendDispatcher::CallbackBase::sendSuccess(RefPtr<JSON::Object>&& partialMessage)
{
if (m_alreadySent)
return;
m_alreadySent = true;
m_backendDispatcher->sendResponse(m_requestId, WTFMove(partialMessage), false);
}
BackendDispatcher::BackendDispatcher(Ref<FrontendRouter>&& router)
: m_frontendRouter(WTFMove(router))
{
}
Ref<BackendDispatcher> BackendDispatcher::create(Ref<FrontendRouter>&& router)
{
return adoptRef(*new BackendDispatcher(WTFMove(router)));
}
bool BackendDispatcher::isActive() const
{
return m_frontendRouter->hasFrontends();
}
void BackendDispatcher::registerDispatcherForDomain(const String& domain, SupplementalBackendDispatcher* dispatcher)
{
ASSERT_ARG(dispatcher, dispatcher);
m_dispatchers.set(domain, dispatcher);
}
void BackendDispatcher::dispatch(const String& message)
{
Ref<BackendDispatcher> protect(*this);
ASSERT(!m_protocolErrors.size());
long requestId = 0;
RefPtr<JSON::Object> messageObject;
{
SetForScope<Optional<long>> scopedRequestId(m_currentRequestId, WTF::nullopt);
RefPtr<JSON::Value> parsedMessage;
if (!JSON::Value::parseJSON(message, parsedMessage)) {
reportProtocolError(ParseError, "Message must be in JSON format"_s);
sendPendingErrors();
return;
}
if (!parsedMessage->asObject(messageObject)) {
reportProtocolError(InvalidRequest, "Message must be a JSONified object"_s);
sendPendingErrors();
return;
}
RefPtr<JSON::Value> requestIdValue;
if (!messageObject->getValue("id"_s, requestIdValue)) {
reportProtocolError(InvalidRequest, "'id' property was not found"_s);
sendPendingErrors();
return;
}
if (!requestIdValue->asInteger(requestId)) {
reportProtocolError(InvalidRequest, "The type of 'id' property must be integer"_s);
sendPendingErrors();
return;
}
}
{
SetForScope<Optional<long>> scopedRequestId(m_currentRequestId, requestId);
RefPtr<JSON::Value> methodValue;
if (!messageObject->getValue("method"_s, methodValue)) {
reportProtocolError(InvalidRequest, "'method' property wasn't found"_s);
sendPendingErrors();
return;
}
String methodString;
if (!methodValue->asString(methodString)) {
reportProtocolError(InvalidRequest, "The type of 'method' property must be string"_s);
sendPendingErrors();
return;
}
Vector<String> domainAndMethod = methodString.splitAllowingEmptyEntries('.');
if (domainAndMethod.size() != 2 || !domainAndMethod[0].length() || !domainAndMethod[1].length()) {
reportProtocolError(InvalidRequest, "The 'method' property was formatted incorrectly. It should be 'Domain.method'"_s);
sendPendingErrors();
return;
}
String domain = domainAndMethod[0];
SupplementalBackendDispatcher* domainDispatcher = m_dispatchers.get(domain);
if (!domainDispatcher) {
reportProtocolError(MethodNotFound, "'" + domain + "' domain was not found");
sendPendingErrors();
return;
}
String method = domainAndMethod[1];
domainDispatcher->dispatch(requestId, method, messageObject.releaseNonNull());
if (m_protocolErrors.size())
sendPendingErrors();
}
}
void BackendDispatcher::sendResponse(long requestId, RefPtr<JSON::Object>&& result)
{
sendResponse(requestId, WTFMove(result), false);
}
void BackendDispatcher::sendResponse(long requestId, RefPtr<JSON::Object>&& result, bool)
{
ASSERT(!m_protocolErrors.size());
Ref<JSON::Object> responseMessage = JSON::Object::create();
responseMessage->setObject("result"_s, WTFMove(result));
responseMessage->setInteger("id"_s, requestId);
m_frontendRouter->sendResponse(responseMessage->toJSONString());
}
void BackendDispatcher::sendPendingErrors()
{
static const int errorCodes[] = {
-32700, -32600, -32601, -32602, -32603, -32000, };
CommonErrorCode errorCode = InternalError;
String errorMessage;
Ref<JSON::Array> payload = JSON::Array::create();
for (auto& data : m_protocolErrors) {
errorCode = std::get<0>(data);
errorMessage = std::get<1>(data);
ASSERT_ARG(errorCode, (unsigned)errorCode < WTF_ARRAY_LENGTH(errorCodes));
ASSERT_ARG(errorCode, errorCodes[errorCode]);
Ref<JSON::Object> error = JSON::Object::create();
error->setInteger("code"_s, errorCodes[errorCode]);
error->setString("message"_s, errorMessage);
payload->pushObject(WTFMove(error));
}
Ref<JSON::Object> topLevelError = JSON::Object::create();
topLevelError->setInteger("code"_s, errorCodes[errorCode]);
topLevelError->setString("message"_s, errorMessage);
topLevelError->setArray("data"_s, WTFMove(payload));
Ref<JSON::Object> message = JSON::Object::create();
message->setObject("error"_s, WTFMove(topLevelError));
if (m_currentRequestId)
message->setInteger("id"_s, m_currentRequestId.value());
else {
message->setValue("id"_s, JSON::Value::null());
}
m_frontendRouter->sendResponse(message->toJSONString());
m_protocolErrors.clear();
m_currentRequestId = WTF::nullopt;
}
void BackendDispatcher::reportProtocolError(CommonErrorCode errorCode, const String& errorMessage)
{
reportProtocolError(m_currentRequestId, errorCode, errorMessage);
}
void BackendDispatcher::reportProtocolError(Optional<long> relatedRequestId, CommonErrorCode errorCode, const String& errorMessage)
{
ASSERT_ARG(errorCode, errorCode >= 0);
if (!m_currentRequestId)
m_currentRequestId = relatedRequestId;
m_protocolErrors.append(std::tuple<CommonErrorCode, String>(errorCode, errorMessage));
}
void BackendDispatcher::reportProtocolError(WTF::DeprecatedOptional<long> relatedRequestId, CommonErrorCode errorCode, const String& errorMessage)
{
if (relatedRequestId)
reportProtocolError(relatedRequestId.value(), errorCode, errorMessage);
else
reportProtocolError(WTF::nullopt, errorCode, errorMessage);
}
template<typename T>
T BackendDispatcher::getPropertyValue(JSON::Object* object, const String& name, bool* out_optionalValueFound, T defaultValue, std::function<bool(JSON::Value&, T&)> asMethod, const char* typeName)
{
T result(defaultValue);
if (out_optionalValueFound)
*out_optionalValueFound = false;
if (!object) {
if (!out_optionalValueFound)
reportProtocolError(BackendDispatcher::InvalidParams, String::format("'params' object must contain required parameter '%s' with type '%s'.", name.utf8().data(), typeName));
return result;
}
auto findResult = object->find(name);
if (findResult == object->end()) {
if (!out_optionalValueFound)
reportProtocolError(BackendDispatcher::InvalidParams, String::format("Parameter '%s' with type '%s' was not found.", name.utf8().data(), typeName));
return result;
}
if (!asMethod(*findResult->value, result)) {
reportProtocolError(BackendDispatcher::InvalidParams, String::format("Parameter '%s' has wrong type. It must be '%s'.", name.utf8().data(), typeName));
return result;
}
if (out_optionalValueFound)
*out_optionalValueFound = true;
return result;
}
static bool castToInteger(JSON::Value& value, int& result) { return value.asInteger(result); }
static bool castToNumber(JSON::Value& value, double& result) { return value.asDouble(result); }
int BackendDispatcher::getInteger(JSON::Object* object, const String& name, bool* valueFound)
{
return getPropertyValue<int>(object, name, valueFound, 0, &castToInteger, "Integer");
}
double BackendDispatcher::getDouble(JSON::Object* object, const String& name, bool* valueFound)
{
return getPropertyValue<double>(object, name, valueFound, 0, &castToNumber, "Number");
}
String BackendDispatcher::getString(JSON::Object* object, const String& name, bool* valueFound)
{
return getPropertyValue<String>(object, name, valueFound, "", &JSON::Value::asString, "String");
}
bool BackendDispatcher::getBoolean(JSON::Object* object, const String& name, bool* valueFound)
{
return getPropertyValue<bool>(object, name, valueFound, false, &JSON::Value::asBoolean, "Boolean");
}
RefPtr<JSON::Object> BackendDispatcher::getObject(JSON::Object* object, const String& name, bool* valueFound)
{
return getPropertyValue<RefPtr<JSON::Object>>(object, name, valueFound, nullptr, &JSON::Value::asObject, "Object");
}
RefPtr<JSON::Array> BackendDispatcher::getArray(JSON::Object* object, const String& name, bool* valueFound)
{
return getPropertyValue<RefPtr<JSON::Array>>(object, name, valueFound, nullptr, &JSON::Value::asArray, "Array");
}
RefPtr<JSON::Value> BackendDispatcher::getValue(JSON::Object* object, const String& name, bool* valueFound)
{
return getPropertyValue<RefPtr<JSON::Value>>(object, name, valueFound, nullptr, &JSON::Value::asValue, "Value");
}
}